为什么这个两个双打的简单计算不准确?

发布于 2024-10-04 10:02:49 字数 443 浏览 1 评论 0原文

可能的重复:
C# (4):双精度减双精度问题 < /p>

86.25 - 86.24 = 0.01

一般来说,我认为上面的说法是正确的,对吗?

但是,如果我输入此内容

        double a = 86.24;
        double b = 86.25;
        double c = b - a;

,我会发现 c = 0.010000000000005116

这是为什么?

Possible Duplicate:
C# (4): double minus double giving precision problems

86.25 - 86.24 = 0.01

generally, I would think the above statement is true right?

However, if I enter this

        double a = 86.24;
        double b = 86.25;
        double c = b - a;

I find that c = 0.010000000000005116

Why is this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风筝在阴天搁浅。 2024-10-11 10:02:49

浮点数(在本例中为双精度数)无法精确表示十进制值。我建议阅读 David Goldberg 的每个计算机科学家都应该了解浮点知识算术

这适用于所有处理浮点数的语言,无论是 C#、Java、JavaScript……这对于任何使用浮点算术的开发人员来说都是必读的。

正如 VinayC 所建议的,如果您需要精确(且速度较慢)的表示形式,请使用 System.Decimal(在 C# 中又称为十进制)。

Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg's What every computer scientist should know about floating-point arithmetic

This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, ... This is essential reading for any developer working with floating point arithmetic.

As VinayC suggests, if you need an exact (and slower) representation, use System.Decimal (aka decimal in C#) instead.

夜吻♂芭芘 2024-10-11 10:02:49

Double 是十进制计算的不正确数据类型,请使用 Decimal。主要原因在于 double 存储数字的方式 - 它本质上是十进制数的二进制近似值。

Double is incorrect data type for decimal calculations, use Decimal for that. Main reason lies in how double stores the number - its essentially a binary approximation of the decimal number.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文