Division in C++ not working as expected

try this:

double f = 3.0/5.0;

this should fix your problem


You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:

 double f = 3.0 / 5;

It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.

Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.

Or simply use double f=.6, that also does the trick...


Try putting a .0 after one of the divisors. This will convert them into floating point literals.

Tags:

C++

Division