2012-02-22 45 views
3

我有這個代碼乘以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); 
    } 

但是,結果並不完全符合我的預期。

enter image description here

這有什麼錯呢?

回答

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); 
} 
0

Int32 * Int32會生成另一個Int32。結果溢出。

嘗試:

System.Int64 x, y; 
1

角色x或y來Int64在乘法。乘法的輸出基於源類型,而不是目標類型。

0

的Int32 *的Int32 ==的Int32

你需要乘

(Int64的)的Int32 *(Int64的)的Int32 == Int64的

前投x和y來的Int64