-2

I am running into a bit of a confusion about one line in this code:

const int maxNum = 4;
int count = 1;
double num;
double total = 0;
double average;

while(count <= maxNum) {
    cout << "please enter a number: " << endl;  
    cin >> num;
    total = total + num;
    cout << "The total is now: " << total << endl;
    count++;
}

cout << "total of 4 digits is: " << total << endl;
//count--;
average = total/count;
cout << "the average of 4 digits is: " << average << "." << endl;

My question is in regards to count--;:

With count--; the average (double) has a decimal point. But when I remove that line of code, the average is shown as only a integer.

What is the significance of this line?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Wrong question. The question you should have asked would be: How do I format floating point I/O stream output? – IInspectable Mar 17 '18 at 11:26
  • `average` is ALWAYS a `double`. That is how typed languages work. If you are referring to why it contains no decimals, that may be due to your numbers added being divided evenly with no remainder. I think what you are asking is how to format your output. https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout should have your answer there. – Sean Mar 17 '18 at 11:30
  • Possible duplicate of [How do I print a double value with full precision using cout?](https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – Sean Mar 17 '18 at 11:31

1 Answers1

2

After the while loop

while(count <= maxNum){
    //...
    count++;
}

count becomes equal to maxNum + 1 that is to 5 though only maxNum numbers were entered. So you need to decrease count before using it in calculating of the average. Though it would be better to use just maxNum instead of count.

It seems that diviting total by 5 you get an integer number.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335