C++ 从数组中找到平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16027566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:00:52  来源:igfitidea点击:

find average value from array

c++arraysaverage

提问by user12074577

for some reason, I am getting a very weird negative nuber as my average for my program, here is my code:

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

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

My output is: -6.84941e+061

我的输出是:-6.84941e+061

回答by taocp

for(int i = 1; i < size; i++){
       //^^should be 0
   sum += array[i];
}
avg = sum / size; //pay attention to truncation when doing integer division

you should pay attention to truncation when divide integers. For example, 10/20 = 0in integer division. meanwhile, you need to start from 0 when computing sum.

整数相除时要注意截断。例如,10/20 = 0在整数除法中。同时,计算 sum 时需要从 0 开始。

Your code should look like the following:

您的代码应如下所示:

 //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