小数四舍五入为关闭(三百〇四分之二百七十六)* 304 [英] decimal rounding is off for (276/304)*304

查看:164
本文介绍了小数四舍五入为关闭(三百〇四分之二百七十六)* 304的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你把下面的code在你的编译器的结果是有点bizar:

If you put the following code in your compiler the result is a bit bizar:

decimal x = (276/304)*304;
double y = (276/304)*304;

Console.WriteLine("decimal x = " + x);
Console.WriteLine("double y = " + y);

结果:

十进制X = 275.99999999999999999999999

decimal x = 275.99999999999999999999999

双Y = 276.0

double y = 276.0

有人可以解释这样对我?我不明白这可能是正确的。

Can someone explain this to me? I don't understand how this can be correct.

推荐答案

三百〇四分之二百七十六=76分之69在这两个基地10和基地2个。一个反复出现的十进制

276/304 = 69/76 is a recurring "decimal" in both base 10 and base 2.

  • 十进制:0.90(789473684210526315)
  • 二进制:0.11(101000011010111100)

因此​​结果被四舍五入,以及由分母乘以可能不会导致在原单分子。这种情况更普遍,被引用的例子为1/3 * 3 = 0.33333333×3 = 0.99999999。

So the result gets rounded off, and multiplying by the denominator may not result in the orginal numerator. A more commonly-cited example of this situation is 1/3*3 = 0.33333333*3 = 0.99999999.

版本给出了确切的答案只是一个巧合。在倍增的舍入误差恰好抵消舍入误差在分裂。

That the double version gives the exact answer is just a coincidence. The rounding error in the multiplication just happens to cancel out the rounding error in the division.

如果这个结果是混乱的,可能是因为你已经听说了有舍入误差和十进制是准确的。但十进制只有精确时间重新presenting的十进制的分数如同0.1(即0.0 0011 0011 ...二进制)。当你有19倍的分母,它不能帮助你。

If this result is confusing, it may be because you've heard that "double has rounding errors and decimal is exact". But decimal is only exact at representing decimal fractions like 0.1 (which is 0.0 0011 0011... in binary). When you have a factor of 19 in the denominator, it doesn't help you.

这篇关于小数四舍五入为关闭(三百〇四分之二百七十六)* 304的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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