简体   繁体   English

在添加到动态数组时转义循环 - C

[英]Escaping loop whilst adding to dynamic array - C

Currently my program allows the user to enter 5 integers which are used to create an average number. 目前我的程序允许用户输入5个用于创建平均数的整数。 This is set to five as after the fifth number is entered the loop is broken. 输入第五个数字后循环被破坏,设置为5。

I am trying to implement a method which will let the user continue to add as many numbers as they like to an array from which i can then use to create an average without a limit on the amount of numbers that can be entered. 我正在尝试实现一种方法,让用户继续向数组中添加任意数量的数字,然后我可以使用这些数据创建平均值,而不限制可输入的数字量。

I have come across a few problems, firstly i cannot create an array which is dyamic as i have no idea how many numbers the user may wish to enter which means i can't give it a definitive size. 我遇到了一些问题,首先我不能创建一个dyamic数组,因为我不知道用户可能希望输入多少个数字,这意味着我无法给它一个明确的大小。

Secondly the way my program currently creates the average is by looping through the elements in the array and adding the consecutively to an integer, from which the the average is made. 其次,我的程序当前创建平均值的方式是循环遍历数组中的元素,并连续地添加一个整数,从中产生平均值。 I cannot specify the limit for the loop to continue running if i cannot determine the array. 如果我无法确定数组,我无法指定循环的限制继续运行。

Hopefully my example explains this better. 希望我的例子更好地解释了这一点。

#include <stdio.h>
#include <string.h>

void main()
{
    int i = 0;
    int arrayNum[5];
    int temp = 1;
    int anotherTemp = 0;
    int answer = 0;


    printf("Enter as many numbers as you like, when finished enter a negative number\n");

    for(i = 0; i < 5; i++)
    {
        scanf("%d", &temp);

        arrayNum[i] = temp;

        anotherTemp = anotherTemp + arrayNum[i];
    }

    answer = anotherTemp / 5;

    printf("Average of %d,%d,%d,%d,%d = %d",arrayNum[0],arrayNum[1],arrayNum[2],arrayNum[3],arrayNum[4],answer);
}

Although this may not be the best way to implement it, it does work when the amount of numbers are specified beforehand. 虽然这可能不是实现它的最佳方法,但是在预先指定数量时它确实有效。

What would be the best way to get around this and allow the user to enter as many number as necessary? 什么是绕过这个并允许用户根据需要输入尽可能多的数字的最佳方法?

Edit: Although i needed to use an array I have decided that it is not necessary as the solution is much simpler without being restricted to it. 编辑:虽然我需要使用数组,但我认为没有必要,因为解决方案更简单,不受限制。

In terms of code simplicity, you might want to check out the realloc() function; 在代码简单性方面,您可能想要检查realloc()函数; you can allocate an initial array of some size, and if the user enters too many numbers call realloc() to get yourself a bigger array and continue from there. 你可以分配一些大小的初始数组,如果用户输入太多的数字,请调用realloc()来获得更大的数组并从那里继续。

You don't, however, actually need to keep the numbers as you go along at all, at least if you only care about the average: 但是,你根本不需要保留数字,至少如果你只关心平均值:

int input;
int sum = 0;
int count = 0;
int average;

while (1) {
    scanf("%d", &input);
    if (input < 0) {
        break;
    }
    sum += input;
    count++;
}

average = sum / count;

If you're trying to compute an average, then you don't need to save the numbers. 如果您尝试计算平均值,则无需保存数字。 Save yourself the work of worrying about the array. 节省自己担心阵列的工作。 Simply accumulate (add) each number to a single total, count each number, then divide when you're done. 只需将每个数字累加(加)到一个总数中,计算每个数字,然后在完成时进行除法。 Two variables are all that you need. 您需要两个变量。

With this method, you aren't in any risk of overflowing your array, so you can use a while loop... while (temp != -1) 使用此方法,您不会有任何溢出数组的风险,因此您可以使用while循环... while(temp!= -1)

Basically you start with a dynamically allocated array with a fixed size, and then allocate a new array that is bigger (say, twice as big as initial size) and copy the stuff from the old array to the new one whenever you run out of space. 基本上你从一个具有固定大小的动态分配数组开始,然后分配一个更大的新数组(比如初始大小的两倍),并在空间不足时将旧数组中的东西复制到新数组中。 。

For the second part of the problem, keep a counter of the number of items the user entered and use it when averaging. 对于问题的第二部分,请保留用户输入的项目数的计数器,并在平均时使用它。

Something like this . 这样的东西。

Use a dynamic array data structure, like Vector in Java (java.util.Vector). 使用动态数组数据结构,如Java中的Vector(java.util.Vector)。

You can implement such a dynamic array yourself easily: 您可以轻松地自己实现这样的动态数组:

  • allocate array of size N 分配大小为N的数组
  • as soon as you need more elements than N, allocate a new bigger array (eg with size N+10), copy the content of the old array into the new array and set your working reference to the new array and your array size variable N to the new size (eg N+10). 一旦你需要比N更多的元素,分配一个新的更大的数组(例如,大小为N + 10),将旧数组的内容复制到新数组中,并将你的工作引用设置为新数组和数组大小变量N到新的大小(例如N + 10)。 Free the old array. 释放旧阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM