multiplication of double with integer precision

后端 未结 5 899
难免孤独
难免孤独 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:11

    You don't have a double with the value of 3.4, since 3.4 isn't representable as a double (at least on the common machines, and most of the exotics as well). What you have is some value very close to 3.4. After multiplication, you have some value very close to 340. But certainly not 399.

    Where are you seeing the 399? I'm guessing that you're simply casting to int, using static_cast, because this operation truncates toward zero. Other operations would likely do what you want: outputting in fixed format with 0 positions after the decimal, for example, rounds (in an implementation defined manner, but all of the implementations I know use round to even by default); the function round rounds to nearest, rounding away from zero in halfway cases (but your results will not be anywhere near a halfway case). This is the rounding used in commercial applications.

    The real question is what are you doing that requires an exact integral value. Depending on the application, it may be more appropriate to use int or long, scaling the actual values as necessary (i.e. storing 100 times the actual value, or whatever), or some sort of decimal arithmetic package, rather than to use double.

提交回复
热议问题