Line 17: You're doing redundant calculations. There's no point in calculating the average until you know the number of items.
But your first actual issue is how you are extracting data from the file. Line 14: You loop until you can't extract more data. This by itself is fine. But then, line 20: You keep trying to extract data. Your line 20 while loop will never be entered.
If you want to re-open your file from the beginning, one way would be:
Thank you for your explanation. But I'm really in a hurry to do it and my brain is paralyzed!
Can you help correct it?
Although the average works well, the rest of them are right in my opinion, but they are not
I told you what was wrong. I'm not going to just write a complete, working program for you. Maybe somebody else will. What you should do is iterate your design based on what I said, and then post the modified version of your code so that it can be critiqued further if you're still having issues.
By the way, prefer the C++ header <cmath> as opposed to <math.h> for C++ code.
@changiz, I think the quote is
"Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime". @Ganado was telling you what was wrong and doing you a favour.
Close the file and reopen it if you want to read the numbers again (although there are far better ways than reading stuff twice).
There's no need to store the numbers either; just form the sum of the numbers and the sum of their squares. There's a simple formula for variance that doesn't require subtracting the average from all numbers first.
#include <iostream>
#include <fstream>
#include <cmath>
int main()
{
if( std::ifstream file{ "random.txt" } )
{
std::size_t n = 0 ; // count
double mean = 0 ; // running mean
double m2n = 0 ; // see: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
// update n, mean and m2n for a new value which has arrived
constauto update = [&] ( double value )
{
// Wellford's algorithm
// "This algorithm is much less prone to loss of precision due to catastrophic cancellation,
// but might not be as efficient because of the division operation inside the loop."
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm
++n ;
constauto delta = value - mean ;
mean += delta / n ;
m2n += delta * ( value - mean ) ;
};
double value ;
while( file >> value ) update(value) ;
if( n > 1 )
{
std::cout << std::fixed
<< " mean: " << mean << '\n'
<< " variance: " << m2n / n << '\n'
<< "sample variance: " << m2n / (n-1) << '\n' ;
}
}
}