Created
April 27, 2010 09:07
-
-
Save earthday/380519 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* 此问题源自于BinarySearch中的求中数的小陷阱。 | |
* 查看了微软的源代码,在1.x时代是如line01所示的方案,显然是有错的。 | |
* 在2.0后改为line03,无错。 | |
* 由于疏忽,我上来写成了line02,于是也出错了,一查看原来是优先级没搞混了。 | |
* | |
*/ | |
using System; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int a = int.MaxValue; | |
int b = int.MaxValue; | |
Console.WriteLine("a is " + a.ToString()); | |
Console.WriteLine("b is " + b.ToString()); | |
Console.WriteLine((a + b) >> 1); // line 01 | |
Console.WriteLine(a + (b - a) >> 1); // line 02 Error: + 的运算符的优先级比 >> 高。。。 | |
Console.WriteLine(a + ((b - a) >> 1)); // line 03 | |
Console.WriteLine(a + (b - a) / 2); // line 04 | |
} | |
} | |
} | |
/* | |
* Console Client | |
* ************************* | |
* | |
* a is 2147483647 | |
* b is 2147483647 | |
* -1 | |
* 1073741823 | |
* 2147483647 | |
* 2147483647 | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment