C#中的32位* 32位数据的问题
问题描述:
我有这个代码乘以32位* 32位。C#中的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);
}
答
Int32 * Int32会生成另一个Int32。结果溢出。
尝试:
System.Int64 x, y;
答
角色x或y来Int64
在乘法。乘法的输出基于源类型,而不是目标类型。
答
的Int32 *的Int32 ==的Int32
你需要乘
(Int64的)的Int32 *(Int64的)的Int32 == Int64的
前投x和y来的Int64