C# C语言中32位*32位数据的一个问题#
我有一个32位乘以32位的代码C# C语言中32位*32位数据的一个问题#,c#,.net,math,int,C#,.net,Math,Int,我有一个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.MaxVa
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);
}
publicstaticvoid RunSnippet()
{
System.Int32 x,y;
System.Int64 z;
System.Random rand=new System.Random(DateTime.Now.毫秒);
对于(int i=0;i<6;i++)
{
x=rand.Next(int.MinValue,int.MaxValue);
y=rand.Next(int.MinValue,int.MaxValue);
z=(x*y);
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);
}
System.Int32 x,y;
System.Int64 z;
System.Random rand=new System.Random(DateTime.Now.毫秒);
对于(int i=0;i<6;i++)
{
x=rand.Next(int.MinValue,int.MaxValue);
y=rand.Next(int.MinValue,int.MaxValue);
z=((Int64)x*y);//通过强制转换x,我们将整个表达式“升级”到64位。
WriteLine(“{0}*{1}={2}”,x,y,z);
}
Int32*Int32生成另一个Int32。结果溢出
尝试:
在乘法运算中,将x或y强制转换为
Int64
。乘法运算的输出基于源类型,而不是目标类型。Int32*Int32==Int32
在乘法运算之前,需要将x和y强制转换为Int64
(Int64)Int32*(Int64)Int32==Int64
System.Int64 x, y;