///////////////////////////

///
Last edited on
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
#include <iostream>
#include <fstream>
#include <cmath>

int main()
{
    const char file_name[] = "C:\\Users\\Josh\\Desktop\\scores.dat" ;

    double sum = 0 ;
    int count = 0 ;

    {
        // sum up all the numbers in the file
        std::ifstream file(file_name) ; // open the file for input
        int number ;
        while( file >> number ) // for each number in the file
        {
            sum += number ;
            ++count ;
        }

        // the file is automagically closed at the end of the scope
    }

    if( count > 0 ) // if we read anything at all
    {
        // compute the mean
        const double mean = sum / count ;

        // read each number and compute the variance
        double sum_square_of_dev_from_mean = 0 ;

        {
            std::ifstream file(file_name) ; // open the file once again
            int number ;

            while( file >> number ) // for each number
            {
                // sum up squares of deviation from mean
                const double deviation_from_mean = number - mean ;
                sum_square_of_dev_from_mean += deviation_from_mean * deviation_from_mean ;
            }
        }

        const double variance = sum_square_of_dev_from_mean / count ;

        // standard deviation is the square root of the variance
        const double standard_deviation = std::sqrt(variance) ;

        // TO DO: print out the results
    }
}
Topic archived. No new replies allowed.