Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange type conversion

Tags:

types

I just can not figure out the following code.

int d = 5;
float f = 3.8f;
int ret = d*f;

The ret is 18, not 19 as I expected. Why?

like image 575
shilk Avatar asked Aug 07 '26 23:08

shilk


1 Answers

There are two issues here. The first is that floating point values are not decimals, so 3.8f is really more like 3.79999999999999999999923 or something like that. The second is that when converting to an int, the system will always truncate the decimal value, rather than rounding.

So if you could peer into the processor, you'd see it doing

3.79999999999999999999923 * 5 = 18.999999999999999999615

Then you remove the non-integer portion:

18
like image 66
StriplingWarrior Avatar answered Aug 11 '26 10:08

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!