奇怪的c#溢出错误

发布于 2024-07-11 19:57:28 字数 430 浏览 4 评论 0原文

有人可以解释一下变量 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天涯离梦残月幽梦 2024-07-18 19:57:28

RHS 是一个 int 乘法,因为表达式的每个部分都是一个 int。 仅仅因为它被分配给 long 并不意味着它是用 long 算术执行的。

将其更改为:

long a = 1024L * 1024 * 1024 * i;

就可以了。 (区别在于第一个 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:

long a = 1024L * 1024 * 1024 * i;

and it'll work. (The difference is the L at the end of the first 1024.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文