C# double addition - strange behaviour

后端 未结 2 1036
慢半拍i
慢半拍i 2020-12-20 02:57
public static void Main()
{
    Dictionary values = new Dictionary();
    values.Add(\"a\", 0.002);
    values.Add(\"b\",         


        
2条回答
  •  情深已故
    2020-12-20 03:15

    Floating point math is inherently not 100% accurate and has error. The order in which you add different numbers together can affect how much floating point error there is. If it's important for these calculations to be completely accurate you should use decimal, not double.

    This doesn't have anything to do with using Sum vs. manually summing the data. In the first you add each number to 615 as you go, in the second you add all of the numbers to each other an then add them to 615. It's a different ordering of adding the same data. Depending on which numbers you use either method could potentially result in more or less error.

提交回复
热议问题