nypran, just keep your code a bit tidier and you can easily spot the biggest problem by yourself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
int main()
{
const std::string fname { "nypran.dat" };
std::ifstream myfile(fname);
if(!fname) {
std::cout << "Failed to open the file " << fname << "!\n";
return 0;
}
double n;
int sum = 0;
double count = -5.0;
double max = 0;
double min = -5.0;
while (myfile >> n) // ------------------------------------------------------ //
{ //
sum += n; //
count++; //
if (n > max) { //
max = n; //
} //
min = n; //
if (n < min) { //
min = n; //
} //
//
std::cout << "The number values is " << count //
<< ".\nThe largest value is " << max //
<< ".\nThe smallest value is " << min //
<< ".\nThe sum is " << sum << ".\n"; //
//
// sum of abs value of each number in the file, divided by how many //
// numbers: //
double ra = (abs(n)) / count; //
//
// square root of (sum of the square of each number in the file divided //
// by how many numbers) //
double rq = sqrt(pow(n, 2) / count); //
//
double mr = abs(min) + max; //
//
std::cout << "r1 = " << ra << "; r2 = " << rq << "; r3 = " << mr << '\n'; //
} // ---------------------------------------------------------------------- //
myfile.close();
return 0;
}
|
I think the main problem is you should wait your reading-from-file loop has ended before performing any calculation (or even output) on your data.
I’d also cut down on ‘tautological’ comments - I mean, when the code is pretty clear itself, comments are usually unnecessary.
May I ask you what are you trying to calculate (just to prove my ignorance at math)?
Because:
1) “sum of abs value of each number in the file, divided by how many numbers”
--> is pretty similar to the arithmetic mean, apart from the ‘abs’.
2) “square root of (sum of the square of each number in the file divided by how many numbers)”
--> this somehow resemble the geometric mean, but in that case, I think it is wrong.