Go - 算术运算符
下表显示了 Go 语言支持的所有算术运算符。假设变量 A 持有 10 个,变量 B 持有 20 个,则:
运算符 | 描述 | 示例 |
---|---|---|
+ | 添加两个操作数 | A + B 得到30 |
- | 从第一个操作数中减去第二个操作数 | A - B 得到-10 |
* | 将两个操作数相乘 | A * B 得到200 |
/ | 将分子除以分母。 | B / A 得到2 |
% | 余数运算符;给出整数除法后的余数。 | B % A 得到0 |
++ | 自增运算符。它将整数值增加 1。 | A++ 得到11 |
-- | 递减运算符。它将整数值减少 1。 | 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
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