c++ - 从数组中查找平均值

标签 c++ arrays average

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

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。 同时计算sum时需要从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

关于c++ - 从数组中查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027566/

相关文章:

c++ - 如何在带有大写文件路径的 Eclipse 中使用 ${include_guard_symbol}?

javascript - 在 Javascript 中从 2 个值和键数组构建一个 Map

javascript - 按数组内其他值分组的特定值的总和

PHP - 如何获取多维数组的特定值

javascript - Mongoose & 获取集合中的平均评分?

mysql - SQL 查询平均值

c++ - 在 Windows 上等待进程或标准输出

c++ - 初始化 2001 x 4001 const float 数组超出堆空间/"CL.exe"退出并出现代码 3 错误

c++ - 使用 OpenGL ES 在 C/C++ 中使用 Sobel 过滤器

command-line - 通用 awk 脚本通过命令行参数计算任何字段的平均值