-5
cout <<  (float(5 / 2)) << endl;

It just prints 2 not 2.5 on the screen, why?
How to do it properly?

  • 2
    Ask yourself: what is the result of `5 / 2`? ... and how do you imagine the cast recovers the information you seem to be seeking? – Dietmar Kühl Mar 14 '18 at 00:25
  • 1
    Possible duplicate of [Why does dividing two int not yield the right value when assigned to double?](https://stackoverflow.com/questions/7571326/why-does-dividing-two-int-not-yield-the-right-value-when-assigned-to-double) – MFisherKDX Mar 14 '18 at 00:30
  • 2
    `(5 / 2)` is integer division, so the result is indeed 2, which you then cast to `float`. You need to use actual floating-point division instead, eg: `(float(5) / 2)` or `(5.0f / 2)` or `(5 / float(2))` or `(5 / 2.0f)` – Remy Lebeau Mar 14 '18 at 00:40
  • Possible duplicate of [What is the behavior of integer division?](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) – François Andrieux Mar 14 '18 at 01:23
  • Btw, why are you using `float` type? Nowadays it's much better to use the `double` type. – Xam Mar 14 '18 at 05:16

1 Answers1

0

The problem isn't that you aren't casting correctly, it is that you aren't doing it at the right time. Because of precedence, the 2 / 5 will be done first, with integer division, leaving 2. This will be then be cast to a double, which stays as 2. If you want to have it as 2.5, you will have to cast them before you do the division. This could look like:

std::cout << (float)5 / (float)2 << std::endl;
Hawkeye5450
  • 672
  • 6
  • 18