问题描述
我检查了文件,长
= 的Int64
的范围超过900,000,000,000,000
I checked the document that long
= int64
has range more than 900,000,000,000,000
下面是我的代码:
int r = 99;
long test1 = r*r*r*r*r;
在运行时,它给了我919965907而不是正确的9509900499。
at runtime it gives me 919,965,907 instead of the correct 9,509,900,499.
另一个测试
long test2 = 99*99*99*99*99;
它拒绝编译,说整数溢出。
It refuses to compile, saying integer overflow.
但是,如果我这样做
long test3 = 10100200300;
这工作得很好。
推荐答案
的问题是字面的99是被当作一个int。如果加上L,它将把它作为一项长期的。要解决你的问题,编译:
The problem is that the literal "99" is being treated as an int. If you add "L" it will treat it as a long. To fix your compilation problem:
long test2 = 99L * 99L * 99L * 99L * 99L;
和修复不正确的结果引发的整数溢出:
And to fix the "incorrect result" caused by integer overflow:
long r = 99;
long test1 = r * r * r * r * r;
的关键点是,表达权=被评估的前的分配给长 - [R
完成的。
The key point is that the expression to the right of the "=" is evaluated before the assignment to long r
is done.
有其它文字后缀你可能有兴趣
There are other literal suffixes you might be interested in:
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
@ m.edmonson,关于你为什么它出来到919965907.发生了什么问题,就是该值是包装围绕int.MaxValue。你可以用一个小的测试程序看到这一点:
@m.edmonson, regarding your question about why it comes out to 919965907. What's happening, is that the value is "wrapping" around int.MaxValue. You can see this with a little test program:
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;
什么是缠绕是什么意思?当你超过 int.MaxValue
1,值蜗居到 int.MinValue
。
int j = int.MaxValue;
j++;
bool isNowMinValue = (j == int.MinValue); // true, the value has "wrapped around"
这是一个有点简单化;如果你搜索整数溢出,你会得到一个更好的解释。这是值得了解如何整数(和其他数字类型)与32位表示:
This is a bit simplistic; if you search for "integer overflow" you will get a better explanation. It's worth understanding how integers (and other numeric types) are represented with 32 bits:
的
这篇关于为什么这会导致很长的整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!