2

I have a really easy question.

    std::cout << std::setprecision(2);
    for (int i = 3; i > 0; i--) {
       std::cout << i / 3.0 << " ";
    }

The above code gives the output:

1 0.67 0.33

Why does i = 3 return an integer number, but i = 2 and i = 1 return a double number? The precision is set to 2 and we are dividing by a double, so I'm confused.

Evg
  • 25,259
  • 5
  • 41
  • 83
Caitlyn T
  • 33
  • 2
  • 4
    Does this answer your question? [Correct use of std::cout.precision() - not printing trailing zeros](https://stackoverflow.com/questions/17341870/correct-use-of-stdcout-precision-not-printing-trailing-zeros) – B. Go Dec 07 '19 at 20:39

1 Answers1

6

setprecision(n); tells the maximum number n of digits to use, not the minimum. Keep in mind that trailing zeroes are automatically discarded, this is what happens when you divide 3 by 3.0, the result is 1.000... but the zeroes get discarded. If you want to get n digits at all times you have to use std::fixed like this:

cout << fixed;
cout << setprecision(2);

and it will give you 2 digits, so for instance 3 / 3.0 will yield 1.00.

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21