Array Average

So I have a homework question and my code compiles fine and runs and I pass 4 out of 5 of my test questions My code is this:


#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <iomanip>

using namespace std;



int main()
{
double user_num[20];
int number_of_numbers;

cout <<"How many numbers do you want? (max 20)" << endl;
cin >> number_of_numbers;

if (number_of_numbers <= 0 || number_of_numbers > 20)
{
cout << "Invalid size. Ending."<< endl;
return 0;
}


for (int counter = 0; counter < number_of_numbers; counter++)
{
cout << "Enter value " << counter << ":" << endl;
cin >> user_num[counter];
}

double total = 0;
double average;

for (int counter =0; counter < number_of_numbers; counter++)
{
total += user_num[counter];
}

average = total / number_of_numbers;

cout << "Average: "<< setprecision(2) << average<< "\n";

cout << "You entered: "<< endl;


for (int x =0; x < number_of_numbers; x++)
{
cout << user_num[x] << endl;

}
return 0;

}




The test i have a problem with is:
5
392.29
-6.52
56.3
8006.31
3344.1

when it tries to find the average of these numbers it gives me
2.4e+003
You entered:
3.9e+002
-6.5
56
8e+003
3.3e+003
Thank you
2.4e3 == 2400

3.9e2 == 390
-6.5 == -6.5
56 == 56
8e3 == 8000
3.3e3 == 3300

Keep in mind you are doing precision 2 so the exact values are slightly different than the numbers mentioned.

390 -6.5 + 56 + 8000 + 3300 = 11739.5 / 5 = 2347.9

or with exact values:
5 + 392.29 -6.52 + 56.3 + 8006.31 + 3344.1 = 11797.48 / 5 = 2359.496

I don't see the problem you are having. It is just rounding up and displaying precision 2 like you said. Maybe you want more precision? Just change setprecision(2) to something higher like 5 or 10?
ok i fixed it thank you very much :)
Last edited on
Just a minor correction giblit. It would be division by 6 and not 5.
You are correct. I was looking at the second thing he posted.
3.9e+002
-6.5
56
8e+003
3.3e+003
which was missing the 5.
closed account (j3Rz8vqX)
You last asked:
ok i need it to only show two numbers after the decimal..how would i achieve that?


giblit's answer:
setprecision(2)


If you apply that to your variable, I'm sure you can get the result.

Tip:
http://www.cplusplus.com/reference/iomanip/setprecision/
Thank you all for your help :)
Topic archived. No new replies allowed.