#include <iostream>
#include <fstream>
int main()
{
constint 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
constdouble 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 )
{
constdouble difference = my_array[i] - average ; // difference may be negative
// deviation is the absolute value of the difference between the number and the average.
constdouble deviation = difference < 0 ? -difference : +difference ;
std::cout << "number: " << my_array[i] << " deviation: " << deviation << '\n' ;
}
}
}