My attempts to find a way to get the average of this array have so far been fruitless. Any help would be appreciated.
#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;
}
voltages file is
100.8
120.4
121.4
111.9
123.4
but can have up to 100 doubles.
To calculate the average of the numbers stored in any C++ container (even raw arrays), use the following approach. Take the sum and divide by the number of elements:
Example code in action:
With std::vector /
With raw array (Note that only the definition of the vector / array changes!)
This code doesn’t check for zero length, which produces a division by zero. This will return a
NaNvalue. This case can be detected in advance by usingif (std::begin(v) == std::end(v)). You can handle such corner cases depending on your need if you don’t want to returnNaN:0.0