2012-07-30 82 views
2

此代碼工作正常奇怪鑄件Math.Pow

Dim bc As Long = Math.Pow(36, ((IBase36.Length - 1) - i)) 

!在VB Math.Pow下返回DOUBLE數據類型。

當我把它轉換成C#我有

long bc = Math.Pow(36, ((IBase36.Length - 1) - i)); 

而且我有一個投語法問題。

如何解決?

+1

你必須小心這樣的代碼。長有19位有效數字,雙數只有15位。當數值變得足夠大時,由於截斷,您可以輕鬆地關閉一位。至少加0.5,所以這不會發生。 – 2012-07-30 18:57:50

回答

1

Math.Pow返回類型double,它在C#中不能隱式轉換爲long,所以它必須通過類型轉換顯式完成。我不太熟悉VB.NET,但是轉換規則可能不那麼嚴格。

2

大概在VB你有Option Strict或者根本沒有宣佈(缺省關閉)

從MSDN

Visual Basic allows conversions of many data types to other data types. 
Data loss can occur when the value of one data type is converted to a data type with 
less precision or smaller capacity. A run-time error occurs if such a narrowing 
conversion fails. Option Strict ensures compile-time notification of these narrowing 
conversions so they can be avoided. 

所以我會改變VB代碼

Option Strict On 

Dim bc As Long = CType(Math.Pow(36, ((IBase36.Length - 1) - i)), Long) 
0

在C#你必須告訴編譯器如果你想得到結果,Math.Pow是一個長整型或者雙整型。

在控制檯應用程序中檢查了這一點。

int value = 2; 
string power = "6"; 
Console.WriteLine("" + (long)Math.Pow(value, (Convert.ToInt16(power) - 1))); 
Console.ReadKey();