C/C++: 1.00000 <= 1.0f = False

后端 未结 3 839
盖世英雄少女心
盖世英雄少女心 2021-01-18 07:49

Can someone explain why 1.000000 <= 1.0f is false?

The code:

#include 
#include 

using namespace std;

int main(in         


        
3条回答
  •  孤独总比滥情好
    2021-01-18 08:25

    The reason is that 1.0/10.0 = 0.1 can not be represented exactly in binary, just as 1.0/3.0 = 0.333.. can not be represented exactly in decimals. If we use

    float step = 1.0f / 8;
    

    for example, the result is as expected.

    To avoid such problems, use a small offset as shown in the answer of mic_e.

提交回复
热议问题