Precision of multiplication by 1.0 and int to float conversion

后端 未结 4 1056
一个人的身影
一个人的身影 2020-12-16 08:53

Is it safe to assume that the condition (int)(i * 1.0f) == i is true for any integer i?

4条回答
  •  清酒与你
    2020-12-16 09:51

    No it is absolutely wrong for all the integers because of the type cast. check code.

    #include 
    
    int main()
    {
        int i = 0;
        for (; i < 2147483647; ++i) {
            if ((int)(i * 1.0f) != i) {
                printf("not equal\n");
                break;
            }
        }
        printf("out of the loop\n");
        getchar();
        return 0;
    }
    

    This code assumes that you take 32 bit integer

提交回复
热议问题