VB.Net算術運算子

2019-10-16 23:02:26

下表顯示了VB.Net支援的所有算術運算子。假設變數A=2,變數B=7,則:

運算子 描述 說明
^ 一個運算元的指定次冪值 B^A = 49
+ 兩個運算元相加 A + B = 9
- 第一個運算元減去第二個運算元 A - B = -5
* 兩個運算元相乘 A * B = 14
/ 第一個運算元除以第二個運算元 B / A = 3.5
\ 第一個運算元除以第二個運算元的整數值 B / A = 3
MOD 模運算子,整數除法後的餘數
B / A = 1

範例

嘗試下面的例子來理解VB.Net中的所有算術運算子:

檔案:arithmetic_operators.vb

Module arithmetic_operators
   Sub Main()
      Dim a As Integer = 21
      Dim b As Integer = 10
      Dim p As Integer = 2
      Dim c As Integer
      Dim d As Single
      c = a + b
      Console.WriteLine("Line 1 - Value of c is {0}", c)
      c = a - b
      Console.WriteLine("Line 2 - Value of c is {0}", c)
      c = a * b
      Console.WriteLine("Line 3 - Value of c is {0}", c)
      d = a / b
      Console.WriteLine("Line 4 - Value of d is {0}", d)
      c = a \ b
      Console.WriteLine("Line 5 - Value of c is {0}", c)
      c = a Mod b
      Console.WriteLine("Line 6 - Value of c is {0}", c)
      c = b ^ p
      Console.WriteLine("Line 7 - Value of c is {0}", c)
      Console.ReadLine()
   End Sub
End Module

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\operators>vbc arithmetic_operators.vb
F:\worksp\vb.net\operators>arithmetic_operators.exe
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.1
Line 5 - Value of c is 2
Line 6 - Value of c is 1
Line 7 - Value of c is 100