Precision & Rounding
Mar 8, 2015 at 11:08pm UTC
Here is the question:
Write a program to compute, and later output to the screen, the average of an arbitrary sequence of integers entered, via the keyboard, by the user. To indicate the end of the sequence, the user inputs a value of -1, a value that is not computed as part of the average.
Here is the code I've written:
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
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const int sValue = -1;
int num, count = 0, sum = 0;
double avg;
cout << "Enter a sequence of numbers (-1 to end the sequence): " ;
do {
cin >> num;
if (num!=sValue){
sum += num;
count++;
}
else
;
} while ( num != sValue );
avg = (double )sum / (double )count;
cout << "Average: " << fixed << setprecision(2) << avg << endl;
return 0;
}
The code works properly, except for this bit:
cout << "Average: " << fixed << setprecision(2) << avg << endl;
I'll get an output like this:
Enter a sequence of numbers (-1 to end the sequence): 5 10 0 0 -1
Average: 3.80
Press any key to continue . . .
Instead of:
Enter a sequence of numbers (-1 to end the sequence): 5 10 0 0 -1
Average: 3.75
Press any key to continue . . .
I'm wondering if anyone can show me how to avoid having the variable avg rounded off.
Last edited on Mar 8, 2015 at 11:19pm UTC
Topic archived. No new replies allowed.