Multiplying int with long result c#

后端 未结 6 1587
自闭症患者
自闭症患者 2020-12-18 07:29

Wonder why. C# .Net 3.5

int a = 256 * 1024 * 1024;
int b = 8;
long c = b * a;
Console.WriteLine(c);//<-- result is -2147483648 

Where do

6条回答
  •  -上瘾入骨i
    2020-12-18 08:03

    The maximum value that int supports is 2147483647. The expected result 2147483648 does not fit in this type range, hence an overflow occurs causing the result to be negative.

    Note that the statement long c = b * a; translates to the following two steps:

    1. Multiple the int values of b and a. The int result is negative due to integer overflow.

    2. Convert the already negative result to long.

    Try casting to long before multiplying:

    long c = b * (long) a;
    

    or declare a be of type long:

    long a = 256L * 1024L * 1024L;
    

提交回复
热议问题