由于某种原因,我得到了一个非常奇怪的负数,作为我程序的平均数,这是我的代码:

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

===============>>#1 票数:5 已采纳

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

  ask by user12074577 translate from so

未解决问题?本站智能推荐: