【发布时间】:2019-08-03 15:15:37
【问题描述】:
我必须计算数组中整数的平均值:
int main(void)
{
int num;
printf("How many elements do you want to add in to the array? --> ");
scanf("%d", &num);
float array[10];
float total, average;
for(int i=0; i<num; i++){
printf("Insert the element: ");
scanf("%f", &array[i]);
total = total + array[i];
}
average = total/num;
printf("The average is: %.2f\n", total);
return 0;
}
输出:
How many elements do you want to add in to the array? --> 3
Insert the element: 5
Insert the element: 6
Insert the element: 7
The average is: 18.00
我预计输出是6.00,但它是18.00。我该如何解决这个问题?
【问题讨论】:
-
首先:在循环之前初始化
total:float total = 0;或简单的total = 0;。 -
printf("The average is: %.2f\n", average); -
你的编译器应该显示一些关于未使用变量
average的警告。听听你的编译器警告。 -
如果它应该是一个整数数组,为什么你把它变成一个浮点数组呢?
-
另外,如果用户输入一个大于 10 的数字作为要添加到数组中的元素数怎么办? (提示:你真的需要一个数组吗?)