.NET 中的双乘法被破坏了吗? [英] Is double Multiplication Broken in .NET?

查看:29
本文介绍了.NET 中的双乘法被破坏了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 C# 中执行以下表达式:

If I execute the following expression in C#:

double i = 10*0.69;

i 是:6.89999999999999995.为什么?

我知道像 1/3 这样的数字很难用二进制表示,因为它有无限重复的小数位,但 0.69 的情况并非如此.而0.69可以很容易地用二进制表示,一个二进制数表示69,另一个表示小数点位置.

I understand numbers such as 1/3 can be hard to represent in binary as it has infinite recurring decimal places but this is not the case for 0.69. And 0.69 can easily be represented in binary, one binary number for 69 and another to denote the position of the decimal place.

我该如何解决这个问题?使用decimal 类型?

How do I work around this? Use the decimal type?

推荐答案

因为您误解了浮点运算以及数据的存储方式.

Because you've misunderstood floating point arithmetic and how data is stored.

事实上,在这种特殊情况下,您的代码实际上并没有在执行时执行任何算术 - 编译器会完成它,然后在生成的可执行文件中保存一个常量.但是,它不能存储 6.9 的精确值,因为该值不能以浮点格式精确表示,就像 1/3 不能以有限十进制表示形式精确存储一样.

In fact, your code isn't actually performing any arithmetic at execution time in this particular case - the compiler will have done it, then saved a constant in the generated executable. However, it can't store an exact value of 6.9, because that value cannot be precisely represented in floating point point format, just like 1/3 can't be precisely stored in a finite decimal representation.

看看这篇文章是否对您有帮助.

这篇关于.NET 中的双乘法被破坏了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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