Why printf round floating point numbers?

前端 未结 3 822
刺人心
刺人心 2020-11-28 14:24

I am trying to print some floating point numbers using printf. For example:

int main()
{
    printf(\"%.1f\",76.75); 
    return 0;
}
         


        
3条回答
  •  情书的邮戳
    2020-11-28 14:50

    In addition to existing answers, note that many C compilers try to follow IEEE 754 for floating-point matters. IEEE 754 recommends rounding according to the current rounding mode for conversions from binary floating-point to decimal. The default rounding mode is “round to nearest and ties to even”. Some compilation platforms do not take the rounding mode into account and always round according to the default nearest-even mode in conversions from floating-point to decimal.

    Since 76.75 represents the number 7675/100 exactly, it is precisely halfway between 76.7 and 76.8. The latter number is considered the “even” one when applying “round to nearest-even”. This is probably why your compilation platform chose to generate this decimal representation as the conversion to decimal of the floating-point number 76.75.

提交回复
热议问题