到目前为止,我试图找到一种方法来获得这个阵列的平均值是徒劳的。任何帮助将不胜感激。
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main( )
{
const int MAX = 100;
double voltages[MAX];
double average;
ifstream thefile("c:\\voltages.txt");
if(!thefile)
{
cout<<"Error opening file"<<endl;
system("pause");
exit(1);
}
for(int count = 0; count < MAX; count++)
{
thefile >> voltages[count];
cout << voltages[count++] << endl;
average = voltages[count++]/count;
if(count == 0 || thefile.eof())
{
break;
}
}
cout << average;
cout << "\n";
system("PAUSE");
return 0;
}
电压文件
100.8
120.4
121.4
111.9
123.4
但最多可以有100次双打。
答案 0 :(得分:2)
要计算任何 C ++容器(甚至是原始数组)中存储的数字的平均值,请使用以下方法。取总和除以元素数:
std::accumulate(std::begin(v), std::end(v), 0.0) / (std::end(v) - std::begin(v));
示例代码:
With std::vector / With raw array(请注意,只有矢量/数组的定义会发生变化!)
此代码不检查零长度,这会产生除零。这将返回NaN
值。可以使用if (std::begin(v) == std::end(v))
预先检测此情况。如果您不想返回NaN
:
0.0
答案 1 :(得分:2)
最好有一个带有总计的双倍,然后是一个计数器,并为平均值做TOTAL / COUNT。不需要矢量和所有这些。
PS:对于fstreams使用.get()而不是.eof()更好一点,因为有时文本编辑器会在末尾添加一个'\ n'字符(给你一个空字符串额外的迭代和可能的错误)。
对于数组和类似内容,在[]内部递增通常也是一个坏主意。最好在括号外使用[count + 1]和/或递增计数。
答案 2 :(得分:0)
使用递归定义平均值:
avg_n= ((n-1)* avg_n_1 + val) / n;
val是第n个数据的值 avg_n是当前平均值 avg_n_1是前一次迭代的平均值(n-1值的平均值)
最后循环中的最后一个语句:
avg_n_1 = avg_n;
通过这种方式,您可以在不事先知道要读取多少值的情况下计算平均值。