关联性数学:(A + B)+ C = A +(B + C)! [英] Associativity math: (a + b) + c != a + (b + c)
问题描述
最近我href="http://ericlippert.com/2008/05/23/$p$pcedence-vs-associativity-vs-order/">老的博客文章由埃里克利珀<经历一个
其中,在写关于关联性,他提到,在C#中,(A + B)+ C
不等同于 A +(B + C)
为A,B,C的某些值。
Recently I was going through an old blog post by Eric Lippert
in which, while writing about associativity he mentions that in C#, (a + b) + c
is not equivalent to a + (b + c)
for certain values of a, b, c.
我无法弄清楚对于什么算术值威力持有真实的类型和范围的原因。
I am not able to figure out for what types and range of arithmetic values might that hold true and why.
推荐答案
在范围内的双
键入
double dbl1 = (double.MinValue + double.MaxValue) + double.MaxValue;
double dbl2 = double.MinValue + (double.MaxValue + double.MaxValue);
第一个是 double.MaxValue
,第二个是 double.Infinity
在的precision的双
类型:
On the precision of the double
type:
double dbl1 = (double.MinValue + double.MaxValue) + double.Epsilon;
double dbl2 = double.MinValue + (double.MaxValue + double.Epsilon);
现在 DBL1 == double.Epsilon
,而 DBL2 == 0
。
和逐字阅读的问题: - )
And on literally reading the question :-)
在检查
模式:
checked
{
int i1 = (int.MinValue + int.MaxValue) + int.MaxValue;
}
I1
是 int.MaxValue
checked
{
int temp = int.MaxValue;
int i2 = int.MinValue + (temp + temp);
}
(注意使用温度
变量,否则编译器会直接给出错误......从技术上讲,即使这将是一个不同的结果:-)编译正确VS没有编译)
(note the use of the temp
variable, otherwise the compiler will give an error directly... Technically even this would be a different result :-) Compiles correctly vs doesn't compile)
这将引发发生OverflowException
...结果是不同的:-)( int.MaxValue
VS 异常
)
this throws an OverflowException
... The results are different :-) (int.MaxValue
vs Exception
)
这篇关于关联性数学:(A + B)+ C = A +(B + C)!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!