【发布时间】:2017-09-30 19:52:30
【问题描述】:
#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
我尝试了很多方法来阻止它,尽管这可能是由于缺乏知识,除了创建一个非常大的数组之外,真的有其他方法吗?
我尝试使用带有 calloc() 的动态数组,但遇到了同样的错误。我不确定在这种方法中还有什么可用的选项。
代码应该取“n”个用户输入值的平均值。
【问题讨论】:
-
在
malloc或calloc之后使用realloc。 -
如果你只是想求任意数量的整数的算术平均值,没有必要存储所有的值。您只需要跟踪条目的总和和数量。
-
但是如果你这样做,你最好不要分配一个长度为
0的数组。