谁能解释为什么输出“Console.WriteLine((int)((0.1 + 0.7)* 10));”是“7”? [英] Can anyone explain Why output of "Console.WriteLine((int) ((0.1 + 0.7) * 10));" is "7"?

查看:177
本文介绍了谁能解释为什么输出“Console.WriteLine((int)((0.1 + 0.7)* 10));”是“7”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Console.WriteLine((int) ((0.1 + 0.7) * 10));



当我在我的机器上运行时,这会给出以下输出。


This gives following Output when i run this on my machine.

7





它将会如果有人解释我为什么得到7,对我有帮助吗?



It will be helpful to me if anybody explain me why i am getting 7?

推荐答案

这很简单,虽然可能很难理解。

尝试这样做:

It's fairly simple, though it may be difficult to understand.
Try doing it like this:
double d = (0.1 + 0.7);
int v = (int)(d * 10);
Console.WriteLine(v);

并在调试器中查看 d 的值。

这不是你所期望的 - 0.8 - 而是7.9999999999999999而不是。



为什么?因为基数10和基数2并不总是很好,而基数10中的实心分数值(如0.1 + 0.7)在基数2中并不那么稳固。



尝试使用小数值:

And look at the value of d in the debugger.
It's not what you expect - 0.8 - but 7.9999999999999999 instead.

Why? Because base 10 and base 2 do not "play nice" all the time, and a fractional value that is "solid" in base 10 (like 0.1 + 0.7) is not so solid in base 2.

Try using decimal values:

decimal d = (0.1M + 0.7M);
int v = (int)(d * 10);
Console.WriteLine(v);

它会做你所期望的。


在这种情况下,0.1和0.7默认是双重类型。

根据OriginalGriff先生的演示文稿,所以两个加法值都预期为7.9999999999999999而不是0.8。

对于解决方案我印象非常深刻

如果我们将使用十进制类型还可以再使用一个解决方案

其中十进制数可以在二进制浮点数0.1中精确表示,对于更接近自然的人工制造的值无论如何都无法真正测量,浮动/双倍更合适。例如,科学数据通常以这种形式表示。在这里,原始值不会以十进制精度开头,因此预期结果保持十进制精度并不重要。



解决方案:

In this case 0.1 and 0.7 are by default double type.
As per OriginalGriff sir presentation so both of addition value will expect 7.9999999999999999 instead of 0.8.
For the solution I am really impressed.
And one more solution can possible if we will use decimal type also
Where decimal numbers are exactly representable in binary floating point 0.1, For values which are more artefacts of nature which can't really be measured exactly anyway, float/double are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy".

Solution:
Console.WriteLine((int)(((decimal)0.1 +(decimal) 0.7) * 10));


欢迎来到每个计算机科学家应该知道的关于浮点运算的内容 [ ^ ]。


这篇关于谁能解释为什么输出“Console.WriteLine((int)((0.1 + 0.7)* 10));”是“7”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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