multiplication of double with integer precision

后端 未结 5 898
难免孤独
难免孤独 2021-01-22 20:35

I have a double of 3.4. However, when I multiply it with 100, it gives 339 instead of 340. It seems to be caused by the precision of double. How could I get around this?

5条回答
  •  伪装坚强ぢ
    2021-01-22 21:09

    Floating-point values are seldom exact. Unfortunately, when casting a floating-point value to an integer in C, the value is rounded towards zero. This mean that if you have 339.999999, the result of the cast will be 339.

    To overcome this, you could add (or subtract) "0.5" from the value. In this case 339.99999 + 0.5 => 340.499999 => 340 (when converted to an int).

    Alternatively, you could use one of the many conversion functions provided by the standard library.

提交回复
热议问题