我有这段代码可以乘以 32 位 * 32 位。
public static void RunSnippet()
{
System.Int32 x, y;
System.Int64 z;
System.Random rand = new System.Random(DateTime.Now.Millisecond);
for (int i = 0; i < 6; i++)
{
x = rand.Next(int.MinValue, int.MaxValue);
y = rand.Next(int.MinValue, int.MaxValue);
z = (x * y);
Console.WriteLine("{0} * {1} = {2}", x, y, z);
}
然而,结果并不是我所期望的。
这是怎么回事?
最佳答案
溢出。结果计算为 32 位整数,然后提升为 64 位。为避免这种情况,请在乘法之前将因子转换为 64 位。
System.Int32 x, y;
System.Int64 z;
System.Random rand = new System.Random(DateTime.Now.Millisecond);
for (int i = 0; i < 6; i++)
{
x = rand.Next(int.MinValue, int.MaxValue);
y = rand.Next(int.MinValue, int.MaxValue);
z = ((Int64)x * y); //by casting x, we "promote" the entire expression to 64-bit.
Console.WriteLine("{0} * {1} = {2}", x, y, z);
}
关于c# - C# 中 32 位 * 32 位数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9402135/