算术运算符
下表显示了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