7

誰かが変数 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 . . .

ありがとう!

4

1 に答える 1

26

式のすべての部分が int であるため、RHS はint乗算です。long に割り当てられているからといって、long 演算で実行されるわけではありません。

次のように変更します。

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

そしてそれはうまくいくでしょう。(違いは、最初の 1024 の末尾の L です。)

于 2008-12-22T10:44:58.443 に答える