Why does this double to int conversion not work?

后端 未结 3 1787
一整个雨季
一整个雨季 2020-12-16 21:28

I\'ve been thoroughly searching for a proper explanation of why this is happening, but still don\'t really understand, so I apologize if this is a repost.

#i         


        
3条回答
  •  难免孤独
    2020-12-16 21:38

    4.1 cannot be exactly represented by a double, it gets approximated by something ever so slightly smaller:

    double x = 4.10;
    printf("%.16f\n", x);  // Displays 4.0999999999999996
    

    So j will be something ever so slightly smaller than 410 (i.e. 409.99...). Casting to int discards the fractional part, so you get 409.

    (If you want another number that exhibits similar behaviour, you could try 8.2, or 16.4, or 32.8... see the pattern?)

    Obligatory link: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

提交回复
热议问题