calc issue

wew
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
#include <iostream>
#include <fstream>

int main()
{
    const int ARRAY_SIZE = 10 ; // size of the array
    int my_array[ARRAY_SIZE] ; // array to hold up to ARRAY_SIZE numbers

    std::ifstream my_file( "numbers.txt" ); // open the file for input

    if( !my_file.is_open() )
    {
        std::cerr << "failed to open input file\n" ;
        return 1 ; // return a non-zero value to indicate failure
    }

    // read the numbers; keep track of how many numbers were actually read
    int count = 0; // count of numbers actually read
    // count < ARRAY_SIZE: up to a maximum of ARRAY_SIZE numbers
    // && my_file >> my_array[count]: and a number was read in successfully
    while( count < ARRAY_SIZE && my_file >> my_array[count] ) ++count ;
    std::cout << count << " numbers were read\n" ;

    if( count > 0 ) // if at least one number was read
    {
        // compute the total
        int total = 0 ;
        for( int i = 0 ; i < count ; ++i ) total += my_array[i] ;
        std::cout << "the total is: " << total << '\n' ;

        // calculate the average double(total): total converted to a floating point value
        const double average = double(total) / count ; // avoid integer division
        std::cout << "the average is: " << average << '\n' ;

        // print each number and it's deviation from the average
        for( int i = 0 ; i < count ; ++i )
        {
            const double difference = my_array[i] - average ; // difference may be negative

            // deviation is the absolute value of the difference between the number and the average.
            const double deviation = difference < 0 ? -difference : +difference ;

            std::cout << "number: " << my_array[i] << "  deviation: " << deviation << '\n' ;
        }
    }
}
Topic archived. No new replies allowed.