当 (a+b)+c != a+(b+c)...

在这周的一次讨论中,有人说(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 那么结果是什么呢,为什么?

 

楼下的人都只知道说蛋疼,没有人想过我最后抛出来的问题吗?

o(︶︿︶)o 唉

 

原文链接:When (a+b)+c != a+(b+c)...

 

原文地址:https://www.cnblogs.com/LoveJenny/p/2209609.html