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

前端 未结 9 1268
余生分开走
余生分开走 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:08

    Since you've identified yourself as unfamiliar with the subtleties of floating point numbers, I'll refer you to this fine paper by David Goldberg: What Every Computer Scientist Should Know About Floating-Point Arithmetic (reprint at Sun).

    After you've been scared by that, the reality is that most of the time floating point is a huge boon to getting calculations done. And modern compilers and languages (including C) handle conversions sensibly so that you don't have to worry about them. Unless you do.

    The points raised about precision are certainly valid. An IEEE float effectively has only 24 bits of precision, which is less than a 32-bit integer. Use of double for intermediate calculations will push all rounding and precision loss out to the conversion back to float or int.

提交回复
热议问题