Why does this double to int conversion not work?

后端 未结 3 1760
一整个雨季
一整个雨季 2020-12-16 21:28

I\'ve been thoroughly searching for a proper explanation of why this is happening, but still don\'t really understand, so I apologize if this is a repost.

#i         


        
3条回答
  •  庸人自扰
    2020-12-16 21:40

    The fix

    int k = (int)(j+(j<0?-0.5:0.5));
    

    The logic

    You're experiencing a problem with number bases.

    Although on-screen, 4.10 is a decimal, after compilation, it gets expressed as a binary floating point number, and .10 doesn't convert exactly into binary, and you end up with 4.099999....

    Casting 409.999... to int just drops the digits. If you add 0.5 before casting to int, it effectively rounds to the nearest number, or 410 (409.49 would go to 409.99, cast to 409)

提交回复
热议问题