设为首页 加入收藏

TOP

当 (a+b)+c != a+(b+c)...
2014-11-23 23:30:01 来源: 作者: 【 】 浏览:1
Tags:...

在这周的一次讨论中,有人说(a+(b+c)) 等于 ((a+b)+c) ,当a, b,c 全部都是简单数据类型,例如int,float,double ...
在数学上当然如此,但是在代码上却并非如此,首先考虑下System.Int32 以及下面的test.cs:

using System;
class Program
{
static void Main(string[] args)
{
int a = int.MaxValue;
int b = 1;
int c = -a;
try { Console.WriteLine(a+(b+c)); }
catch(Exception e) { Console.WriteLine(e.Message); }

try { Console.WriteLine((a+b)+c); }
catch(Exception e) { Console.WriteLine(e.Message); }
}
}

使用csc.exe test.cs 编译代码,运行test.exe,结果如下:
1
1
很容易理解。现在使用csc.exe /checked test.cs来进行编译,运行test.exe,结果如下:
1
Arithmetic operation resulted in an overflow.

所以,操作的顺序的确产生了差异,现在考虑下一个更有意思的例子,浮点数数字..float
using System;
class Program
{
static void Main(string[] args)
{
float a = float.MaxValue;
float b = -a;
float c = -1;
Console.WriteLine(a+(b+c));
Console.WriteLine((a+b)+c);
}
}

使用csc.exe test.cs进行编译,运行test.exe,结果如下:
0
-1

现在问你一个问题:



如果使用csc.exe /checked test.cs 进行编译,运行test.exe 那么结果是什么呢,为什么?
原文链接:When (a+b)+c != a+(b+c)...

作者:LoveJenny    

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇printf的工作顺序和++问题 下一篇static的滥用与变态的阉割

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: