I have a program that can generate a random integer every 1/10 second. Here is the code:
int main()
{
ofstream myfile;
int max;
cout << "Max number: ";
cin >> max;
for (int i = 0; i < max; ++i)
{
myfile.open("test.txt",fstream::app);
myfile << random_int() << "\n";
myfile.close();
this_thread::sleep_for(chrono::milliseconds(100));
}
return 0;
}
int random_int()
{
return rand() % 10;
}
Now the question is, I need to write a program that calculate then output the average in the same rate. If the output of the number generator is:
1
2
3
4
5
The output of the average calculator should be
1
1
2
2
3
Every 1/10 second the program will output a number.
Note: The max number could be from 0 to couple millions. Calculating the average by adding all previous number during the time interval won't be ideal.
I am a sophomore student and a research assistant in a university. This is a simplified version of a problem that I encounter currently. Any suggestion will be greatly appreciated.
Update: Thanks for the help from Fei Xiang and oklar. Yes, remember the previous sum is the only way to make the calculation in time. However, since the random generator output file is changing constantly and the new output is appended to the old outputs, I am not sure how to get the most current data efficiently.