Avoiding integer division for calculating average?

Hi all,

I created a program that takes in 3 test scores that the user inputs using an array. The program then calculates the total and average of the 3 scores.

Because the array is an int, the program accepts the input as integers only, but when it comes to actually calculating the average of the 3 integers, I would like the program to output the average using regular division -- not integer division.

Here is the faulty code I have now:
(average always comes out as an integer)

1
2
3
4
5
float average = (scores[0] + scores[1] + scores[2])/(3);
cout << "\t\t\t\t      Total: ";
cout << (scores[0] + scores[1] + scores[2]);
cout << "\n\t\t\t\t    Average: ";        
cout << showpoint << setprecision(1) << fixed << average << "%";      


So how would I go about adding the array elements, which are taken in as integers, and dividing them in a way that doesn't result in integer division, but instead in precise division with decimals included?

As always, thank you.

Last edited on
Try float average = (scores[0] + scores[1] + scores[2])/(3.0f);
It works! That was a very simple solution. Thank you!
When you divide with even one double or float you will get a double or float as an answer (respectively.) Remember that you can always cast a variable to a double or float also.

Example:
1
2
int a = 7, b = 3;
cout << (double)a / b; //cast a to a double, then divide 
Topic archived. No new replies allowed.