奇怪的c#溢出错误
有人可以解释一下变量 a 溢出的原因吗? 请注意,b 比 a 大。
static void Main(string[] args)
{
int i = 2;
long a = 1024 * 1024 * 1024 * i;
long b = 12345678901234567;
System.Console.WriteLine("{0}", a);
System.Console.WriteLine("{0}", b);
System.Console.WriteLine("{0}", long.MaxValue);
}
-2147483648
12345678901234567
9223372036854775807
Press any key to continue . . .
谢谢!
Can someone explain me the reason of overflow in variable a? Note that b is bigger than a.
static void Main(string[] args)
{
int i = 2;
long a = 1024 * 1024 * 1024 * i;
long b = 12345678901234567;
System.Console.WriteLine("{0}", a);
System.Console.WriteLine("{0}", b);
System.Console.WriteLine("{0}", long.MaxValue);
}
-2147483648
12345678901234567
9223372036854775807
Press any key to continue . . .
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
RHS 是一个 int 乘法,因为表达式的每个部分都是一个 int。 仅仅因为它被分配给 long 并不意味着它是用 long 算术执行的。
将其更改为:
就可以了。 (区别在于第一个 1024 末尾的 L。)
The RHS is an int multiplication because every part of the expression is an int. Just because it's being assigned to a long doesn't mean it's performed with long arithmetic.
Change it to:
and it'll work. (The difference is the L at the end of the first 1024.)