C# loss of precision when dividing doubles

前端 未结 6 760
执笔经年
执笔经年 2021-01-12 07:05

I know this has been discussed time and time again, but I can\'t seem to get even the most simple example of a one-step division of doubles to result in the expected, unroun

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 07:39

    It's the usual floating point imprecision. Not every number can be represented as a double, and those minor representation inaccuracies add up. It's also a reason why you should not compare doubles to exact numbers. I just tested it, and result.ToString() showed 28 (maybe some kind of rounding happens in double.ToString()?). result == 28 returned false though. And (int)result returned 27. So you'll just need to expect imprecisions like that.

提交回复
热议问题