出于某种原因,我的程序平均得到一个非常奇怪的负数,这是我的代码:
int sum, avg;
int size;
size = sizeof(array) / sizeof(array[0]);
sum = 0;
avg = 0;
for(int i = 0; i < size; i++){
sum += array[i];
}
avg = sum / size
我的输出是:-6.84941e+061
for(int i = 1; i < size; i++){
//^^should be 0
sum += array[i];
}
avg = sum / size; //pay attention to truncation when doing integer division
整数除法时要注意截断。例如,10/20 = 0
在整数除法中。同时,计算总和时需要从 0 开始。
您的代码应如下所示:
//the average may not necessarily be integer
float avg = 0.0; //or double for higher precision
for (int i = 0; i < size; ++i)
{
sum += array[i];
}
avg = ((float)sum)/size; //or cast sum to double before division