位置:首页 > 高级语言 > Go语言在线教程 > Go语言算术运算符

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