为什么这会导致长整数溢出

col*_*ang 19 c# integer

我检查了文件long= int64已范围超过900,000,000,000,000

这是我的代码:

int r = 99;
long test1 = r*r*r*r*r;
Run Code Online (Sandbox Code Playgroud)

在运行时它给了我919,965,907而不是正确的9,509,900,499.

另一个考验

long test2 = 99*99*99*99*99;
Run Code Online (Sandbox Code Playgroud)

它拒绝编译,说整数溢出.

但如果我这样做

long test3 = 10100200300;
Run Code Online (Sandbox Code Playgroud)

这很好用.

Joh*_*hnD 48

问题是文字"99"被视为int.如果你添加"L",它将把它视为一个长期.要修复编译问题:

long test2 = 99L * 99L * 99L * 99L * 99L;
Run Code Online (Sandbox Code Playgroud)

并修复整数溢出导致的"错误结果":

long r = 99;
long test1 = r * r * r * r * r;
Run Code Online (Sandbox Code Playgroud)

关键点是完成赋值之前评估"="右侧的表达式long r.

您可能还有其他一些字面后缀:

Type    Suffix    Example
uint    U or u    100U
long    L or l    100L
ulong   UL or ul  100UL
float   F or f    123.45F
decimal M or m    123.45M
Run Code Online (Sandbox Code Playgroud)

@ m.edmonson,关于为什么它出现在919965907的问题.发生了什么,是值"包裹"在int.MaxValue周围.你可以通过一个小测试程序看到这个:

int i = 99; // 99
i *= 99;    // 9801
i *= 99;    // 970299
i *= 99;    // 96059601
i *= 99;    // 919965907        should be 9509900499 but comes out to 919965907
            //                      which is (9509900499 % int.MaxValue)

long k = 9509900499 % int.MaxValue;
Run Code Online (Sandbox Code Playgroud)

什么是"环绕"?超过int.MaxValue1时,值"返回" int.MinValue.

int j = int.MaxValue;
j++;

bool isNowMinValue = (j == int.MinValue);   // true, the value has "wrapped around"
Run Code Online (Sandbox Code Playgroud)

这有点过分了; 如果你搜索"整数溢出",你会得到一个更好的解释.值得理解整数(和其他数字类型)如何用32位表示:

http://en.wikipedia.org/wiki/Signed_number_representations


Tim*_*ham 5

它使用整数乘法:

long r = 99;
long test1 = r*r*r*r*r;
Run Code Online (Sandbox Code Playgroud)