c# - 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
我如何得到正确的数学结果?
解决方案
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
推荐阅读
- regex - 在正则表达式集中找到尽可能多的正则表达式匹配的字符串
- chunked-encoding - 错误——加载资源失败:net::ERR_INCOMPLETE_CHUNKED_ENCODING
- c# - ASP.NET MVC5 实现 SQL 查询工具
- javascript - 如何在 Javascript 中为本田汽车模型及其功能构建对象表示
- python - python - 这部分使代码重复两次,我该如何解决
- c# - 如何在以下代码中返回静态变量?
- flask - 我无法为 reset_password() 解决烧瓶中的错误
- angular - 多个构建环境上的角度应用程序的版本标记
- android - 华为钱包套件:添加密码失败错误
- macos - 启动守护程序无法访问钥匙串条目