Go語言算術運算子範例

2019-10-16 23:16:36

算術運算子

下表顯示了Go語言支援的所有算術運算子。假設變數 A 的值為 10,變數 B 的值為 20,則:

算術運算子範例

運算子 描述 範例
+ 新增兩個運算元 A + B = 30
- 從第一個運算元中減去第二個運算元 A - B = 10
* 將兩個運算元相乘 A * B = 200
/ 將分子除以分母 B / A = 2
% 模數運算子,以及整數除法的餘數 B % A = 0
++ 增加(遞增)運算子,將整數值加一 A++ = 11
-- 相減(遞減)運算子,將整數值減一 A— = 9

範例

嘗試以下範例來了解Go程式設計語言中的所有算術運算子:

package main

import "fmt"

func main() {

   var a int = 21
   var b int = 10
   var c int

   c = a + b
   fmt.Printf("Line 1 - Value of c is %d\n", c )
   c = a - b
   fmt.Printf("Line 2 - Value of c is %d\n", c )
   c = a * b
   fmt.Printf("Line 3 - Value of c is %d\n", c )
   c = a / b
   fmt.Printf("Line 4 - Value of c is %d\n", c )
   c = a % b
   fmt.Printf("Line 5 - Value of c is %d\n", c )
   a++
   fmt.Printf("Line 6 - Value of a is %d\n", a )
   a--
   fmt.Printf("Line 7 - Value of a is %d\n", a )
}

當編譯和執行上述程式時,它產生以下結果:

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 c is 2
Line 5 - Value of c is 1
Line 6 - Value of a is 22
Line 7 - Value of a is 21