【发布时间】:2013-01-31 00:11:56
【问题描述】:
到目前为止,我试图找到一种方法来获取该数组的平均值的尝试都没有结果。任何帮助将不胜感激。
#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 个双打。
【问题讨论】:
-
您在每次循环迭代中增加
count3 次。你确定那是故意的吗?无论如何,我会选择一个向量来读取文件,然后将std::accumulate除以大小。 -
为什么要计算每个循环的平均值。这是浪费效率。使用双精度数作为总数,并在循环外最后除以计数器。
-
此外,您永远不会对任何地方的电压值求和,这是计算平均值的一个非常重要的步骤。
-
while (thefile.eof()) { thefile >> tmp;总和+=tmp ; cnt++ } return (cnt==0)?0: sum/cnt;
标签: c++ arrays file-io double average