Can I compare and add a floating-point number to an integer in C?

前端 未结 9 1270
余生分开走
余生分开走 2020-12-14 02:50

Can I compare a floating-point number to an integer?

Will the float compare to integers in code?

float f;     // f has a saved predetermined floating         


        
相关标签:
9条回答
  • 2020-12-14 03:27

    About that, the notation 1.0 is of type double so the comparison is made in double by type promotion rules like said before. 1.f or 1.0f is of type float and the comparison would have been made in float. And it would have worked as well since we said that 2^23 first integers are representible in a float.

    0 讨论(0)
  • 2020-12-14 03:33

    The first one will work fine. 100 will be converted to a float, and IEE754 can represent all integers exactly as floats, up to about 223.

    The second one will also work but will be converted into an integer first, so you'll lose precision (that's unavoidable if you're turning floats into integers).

    0 讨论(0)
  • 2020-12-14 03:35

    Can you compare a float and an integer, sure. But the problem you will run into is precision. On most C/C++ implementations, float and int have the same size (4 bytes) and wildly different precision levels. Neither type can hold all values of the other type. Since one type cannot be converted to the other type without loss of precision and the types cannot be native compared, doing a comparison without considering another type will result in precision loss in some scenarios.

    What you can do to avoid precision loss is to convert both types to a type which has enough precision to represent all values of float and int. On most systems, double will do just that. So the following usually does a non-lossy comparison

    float f = getSomeFloat();
    int i = getSomeInt();
    if ( (double)i == (double)f ) { 
       ...
    }
    
    0 讨论(0)
提交回复
热议问题