exact representation of floating points in c

前端 未结 9 917
离开以前
离开以前 2020-12-01 17:40
void main()
{
    float a = 0.7;

    if (a < 0.7)
        printf(\"c\");
    else
        printf(\"c++\");
} 

In the above question for 0.7, \"

相关标签:
9条回答
  • 2020-12-01 17:56

    A good reference for this is What Every Computer Scientist Should Know About Floating-Point Arithmetic. You can use higher precision types (e.g. double) or a Binary Coded Decimal (BCD) library to achieve better floating point precision if you need it.

    0 讨论(0)
  • 2020-12-01 18:03

    If you want to know how float/double is presented in C(and almost all languages), please refert to Standard for Floating-Point Arithmetic (IEEE 754) http://en.wikipedia.org/wiki/IEEE_754-2008

    Using single-precision floats as an example, here is the bit layout:  
    seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm    meaning  
    31                              0    bit #  
    s = sign bit, e = exponent, m = mantissa
    
    0 讨论(0)
  • 2020-12-01 18:04

    Floating point numbers in C/C++ are represented in IEEE-754 standard format. There are many articles on the internet, that describe in much better detail than I can here, how exactly a floating point is represented in binary. A simple search for IEEE-754 should illuminate the mystery.

    0 讨论(0)
  • 2020-12-01 18:04

    0.7 is a numeric literal; it's value is the mathematical real number 0.7, rounded to the nearest double value.

    After initialising float a = 0.7, the value of a is 0.7 rounded to float, that is the real number 0.7, rounded to the nearest double value, rounded to the nearest float value. Except by a huge coincidence, you wouldn't expect a to be equal to 0.7.

    "if (a < 0.7)" compares 0.7 rounded to double then to float with the number 0.7 rounded to double. It seems that in the case of 0.7, the rounding produced a smaller number. And in the same experiment with 0.8, rounding 0.8 to float will produce a larger number than 0.8.

    0 讨论(0)
  • 2020-12-01 18:08

    The internal representation is IEE754.

    You can also use this calculator to convert decimal to float, I hope this helps to understand the format.

    0 讨论(0)
  • 2020-12-01 18:09

    floats will be stored as described in IEEE 754: 1 bit for sign, 8 for a biased exponent, and the rest storing the fractional part.

    Think of numbers representable as floats as points on the number line, some distance apart; frequently, decimal fractions will fall in between these points, and the nearest representation will be used; this leads to the counterintuitive results you describe.

    "What every computer scientist should know about floating point arithmetic" should answer all your questions in detail.

    0 讨论(0)
提交回复
热议问题