Float doesn't change when i add 0.1 to it

送分小仙女□ 提交于 2019-12-19 07:42:20

问题


I am quite a newbie to c. So when i writing a small game demo, i face a really strange problem.

 void testC()
 {
     float a = 825300160;
     float b = a + 0.1;
     assert(a != b);
 }

The above assert statement can't passed. Very strange.
My environment is mac os ml. gcc 4.2.1


回答1:


The fractional portion of a float consists of 23 bits. You need 30 bits to represent 825300160, so the less significant portion of the number is dropped. Adding .1 does not make a difference - you need to add roughly 32 for the number to change:

float a = 825300160;
float b = a + 31.5;
assert(a != b); // No change is detected
float c = a + 32;
assert(a != c); // Change is detected



回答2:


There's not enough precision in the float type. If you really need to distinguish a 0.1 addition to a number as large as 825300160, use double.




回答3:


As this site shows, both a and b would be represented as

0 10011100 10001001100010001010011

in the IEEE standard for floats, where the first bit is the sign, the next 8 are the exponent, and the remaining 23 the mantissa. There's just not enough space in those 23 bits to represent the difference, because the exponent is so large.



来源:https://stackoverflow.com/questions/13557036/float-doesnt-change-when-i-add-0-1-to-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!