是双倍增破碎的.NET? [英] Is double Multiplication Broken in .NET?

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

问题描述

如果我执行下面的EX pression在C#:<​​/ P>

 双I = 10 * 0.69;
 

是: 6.8999999999999995 。为什么?

予理解数字如三分之一可很难重新present二进制因为它具有无穷的重复小数位,但是,这不是为0.69的情况。 psented二进制,一个二进制数为69,另一个和0.69可以很容易地重新$ P $表示小数点的位置。

我如何解决此问题?使用十进制键入<?/ P>

解决方案

由于你误会了浮点运算和数据的存储方式。

其实,你的code未实际执行在执行时的任何运算在这种特殊情况下 - 中的编译器的会做它,然后将其保存恒定在生成的可执行文件。然而,它的不能的存储6.9的精确值,因为该值不能psented浮点格式点precisely重新$ P $,就像1/3不能precisely存储在一个有限小数重presentation。

看看这篇文章帮助你。

If I execute the following expression in C#:

double i = 10*0.69;

i is: 6.8999999999999995. Why?

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.

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

解决方案

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

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.

See if this article helps you.

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

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