//Purpose: This program reads floating point numbers until the end-of-file
// while counting and summing the input data items.
// After the while loop, it finds the average.
// Finally, display the counter, sum, and average.
//include files...
#include <iostream>
usingnamespace std;
int main()
{
//Variable declaration
float number; // storage for the number read
float average;
float sum;
int counter;
//Initialize variables
counter = 0;
sum = 0;
// loop until failed input data stream
while ( cin )
{
cout <<"The number read is "<< number << endl; //don't change this line
cin >> number; // process number and read the next number
counter++;
sum = sum + counter;
}
//Compute the average. Make sure there is no divide by zero.
if ( counter != 0)
average = sum / counter;
//Display the results
cout << endl;
cout << "Number of input data items: " << counter << endl;
cout << "Sum of input data items: " << sum << endl;
cout << "Average of input data items: " << average << endl << endl;
This is the output I'm getting entering 1,2,3,4. There's some garbage being output before the actual number that I want to add.
The number read is -1.33754e-05
The number read is 1
The number read is 2
The number read is 3
The number read is 4
Number of input data items: 5
Sum of input data items: 15
Average of input data items: 3
I made a few tweaks to the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
counter = 0;
sum = 0;
//added this outside the while loop
cin >> number;
// loop until failed input data stream
while ( cin )
{
cout <<"The number read is "<< number << endl; //don't change this line
counter++;
sum = sum + number; //not counter
cin >> number; // process number and read the next number
}
This outputs
The number read is 1
The number read is 2
The number read is 3
The number read is 4
Number of input data items: 4
Sum of input data items: 10
Average of input data items: 2.5