首页 > 解决方案 > 1 + 2 - 3 * 4 / 5 的数学结果错误。得到 1 而不是 0.6

问题描述

我正在编写一个计算器类,它将数学表达式作为字符串,解决它,并将结果作为双精度返回。

到目前为止,一切都按预期工作。

我的问题是我的一个单元测试失败了。

// this test should pass but fails with messag:
// Assert.AreEqual failed. Expected:<0,6000000000000001>. Actual:<1>. 
Assert.AreEqual(Solve("1 + 2 - 3 * 4 / 5"), ( 1 + 2 - 3 * 4 / 5));

您可以使用以下代码测试问题:

using System;

public class Program
{
    public static void Main()
    {
        double r = 1 + 2 - 3 * 4 / 5; // should be 0.6 or 0.6000000000000001
        Console.WriteLine(r == 1); // Prints True
        Console.WriteLine("Result: " + r); // Prints 1
    }
}

小提琴https://dotnetfiddle.net/rRZtAu

我如何得到正确的数学结果?

标签: c#

解决方案


1结果是因为您正在对所有整数值执行数学运算。

如果你想要结果double,那么你至少一个值应该是除法的两倍

尝试,

double r = 1 + 2 - 3 * 4 / 5.0;

一步一步执行,

= 1 + 2 - 3 * 4 / 5.0
       //^^^^  multiplication will execute first = 12
= 1 + 2 - 12 / 5.0
      //^^^^^^^^  this will return 2.4
= 1 + 2 - 2.4   
  //^^^^^^^  0.4

= 0.6  > result

推荐阅读