在这个例子中,我们将使用Golang中的模子和除法运算符从给定的分子(股息)和分母(除数)中找出商和余数。
商是数学中除法运算的一个结果。在Golang中,除法运算符/被使用并应用于整数。
余数是数学中模子运算符的结果。符号%在Golang中被定义。
例子:寻找商和余数
下面的例子解释了Golang的算术运算符
- 除法运算符 - 分子与分母相除。
- 模数运算符 - 为除法运算符的结果输出余数。
以下是Golang中除法和模数运算的例子
package main
import (
"fmt"
)
func main() {
numerator := 40
denominator := 20
/*quotient := numerator / denominator
remainder := numerator % denominator */
// above commented code can be replaced with single line as below
quotient, remainder := numerator/denominator, numerator%denominator
fmt.Println("quotient result:", quotient)
fmt.Print("remainder result:", remainder)
}
上述程序的输出是
quotient result: 2
remainder result:0
在上面的例子中,两个整数40(分子)和20(分母)被储存在一个变量中--分子和分母。
使用/运算符将40除以20,结果存储在商变量中。40/20的余数为0,存储在余数变量中。
商变量和余数变量的值都用fmt println函数打印到控制台。