C# float bug? 0.1 - 0.1 = 1.490116E-08

后端 未结 5 576
自闭症患者
自闭症患者 2020-12-03 16:23

What\'s going on?! Subtraction works fine until I get to 0.1 - 0.1. I\'m in visual c# 2008 using the nonoba.com API.

Console.WriteLine(\"hit! \" + Users[targ         


        
5条回答
  •  庸人自扰
    2020-12-03 17:25

    That seems pretty normal for floating point math... you always have to check against a small delta to account for imperceptible rounding differences. Depending on the scenario, decimal might be what you want.

    Basically, unless you can be sure that it is exactly the same 0.1 in both cases (i.e. nothing has been done to them), you aren't likely to get zero; in general you'll get something very nearly zero. With decimal you'll usually get more what you expect intuitively.

    See also Jon Skeet's pages here:

    • Binary floating point
    • Decimal floating point

提交回复
热议问题