VB.NET中的除法運算符有兩個:/(浮點除法)、\(整數除法)
C#中的除法運算符只有一個:/(除法)
VB.NET中的除法運算符與C#中的除法運算符存在很大的差異,使用時注意區分。
關於VB.NET中的除法運算符的介紹(摘自MSDN):
/(浮點除法):將兩個數相除並返回以浮點數表示的結果。
所得結果的數據類型取決於操作數的類型。 下表顯示如何確定結果的數據類型。
操作數數據類型 |
結果數據類型 |
兩個表達式都是整數數據類型(SByte、Byte、Short、UShort、Integer、UInteger、Long、ULong) | Double |
一個表達式為 Single 數據類型,而另一個表達式不為 Double | Single |
一個表達式為 Decimal 數據類型,而另一個表達式不為 Single 或 Double | Decimal |
任一表達式為 Double 數據類型 | Double |
Boolean | SByte | Byte | Short | UShort | Integer | UInteger | Long | ULong | |
Boolean | Boolean | SByte | Short | Short | Integer | Integer | Long | Long | Long |
SByte | SByte | SByte | Short | Short | Integer | Integer | Long | Long | Long |
Byte | Short | Short | Byte | Short | UShort | Integer | UInteger | Long | ULong |
Short | Short | Short | Short | Short | Integer | Integer | Long | Long | Long |
UShort | Integer | Integer | UShort | Integer | UShort | Integer | UInteger | Long | ULong |
Integer | Integer | Integer | Integer | Integer | Integer | Integer | Long | Long | Long |
UInteger | Long | Long | UInteger | Long | UInteger | Long | UInteger | Long | ULong |
Long | Long | Long | Long | Long | Long | Long | Long | Long | Long |
ULong | Long | Long | ULong | Long | ULong | Long | ULong | Long | ULong |
如果 \ 運算符兩個操作數中的任何一個為 Decimal、Single 或 Double,則 Visual Basic 在運算前會嘗試將其轉換為 Long,並且運算的結果數據類型為 Long。如果 Option Strict 為 On,將產生編譯器錯誤。 如果 Option Strict 為 Off,若值超出 Long 數據類型 (Visual Basic) 的范圍,則可能會產生 OverflowException。 轉換為 Long 也服從“四舍六入五成雙”。如果除數或被除數計算結果等於 Nothing,則將其視為零。
關於C#中的除法運算符的介紹(摘自MSDN):
/(除法): 將兩個數相除並返回除數和被除數的數據類型中精度高的數據類型。
執行除法前,編譯器會將除數和被除數的數據類型統一成兩者類型中精度高的數據類型。返回的運算結果的類型也是兩者類型中精度高的數據類型。例如:兩個整數相除的結果始終為一個整數。 一個整數和一個Double型相除,返回結果為Double型。但是需要注意一點,Double和Decimal不能直接進行算術運算,必須先顯式的將兩者類型進行統一,之后才能進行運算,Double和Decimal不能直接進行運算的原因是兩者之間不能進行隱式的類型轉換。