为什么这个简单的两盘双打的计算不准确? [英] Why is this simple calculation of two doubles inaccurate?

查看:186
本文介绍了为什么这个简单的两盘双打的计算不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
C#(4):双减双精度给予问题

86.25 - 86.24 = 0.01

86.25 - 86.24 = 0.01

通常,我会认为上述声明真实正确的。

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

不过,如果我进入这个

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



我发现,C = 0.010000000000005116

I find that c = 0.010000000000005116

这是为什么?

推荐答案

浮点数(在这种情况下,双打)不能完全代表十进制值。我会推荐阅读大卫·戈德堡的 每台计算机科学家应该知道浮点什么算术

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

这适用于浮点数处理所有的语言,无论是C#,Java和JavaScript的,...这是至关重要的阅读任何开发者与浮点运算工作。

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.

由于VinayC建议,如果您需要确切的(慢)表示,使用 System.Decimal (又名小数在C#)来代替。

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

这篇关于为什么这个简单的两盘双打的计算不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆