cout << (float(5 / 2)) << endl;
It just prints 2
not 2.5
on the screen, why?
How to do it properly?
cout << (float(5 / 2)) << endl;
It just prints 2
not 2.5
on the screen, why?
How to do it properly?
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;