Go語言算術運算符
下表列出了所有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