我有这个代码,乘以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);
}
Run Code Online (Sandbox Code Playgroud)
但是,结果并不完全符合我的预期.

这有什么问题?
Dan*_*her 10
溢出.结果计算为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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |