Golang 查找给定数字的模数
Go语言提供了内置的支持基本常量和数学函数,以通过math包对数字执行操作。您可以通过math包提供的Mod()函数获取指定a/b的模数或浮点余数。因此,您需要在程序中使用import关键字添加math包,以便访问Mod()函数。
语法:
func Min(a,b float64)float64
- 在此函数中,结果的大小小于b,其符号与a的符号相同。
- 如果您在此函数中传递-Inf或+ Inf(例如Mod(-Inf,b)或Mod(+ Inf,b)),则此函数将返回NaN。
- 如果您在此函数中传递NaN(例如Mod(NaN,b)),则此函数将返回NaN。
- 如果您在此函数中传递b = 0(例如Mod(a,0)),则此函数将返回NaN。
- 如果您在此函数中传递-Inf或+ Inf(例如Mod(a,-Inf)或Mod(b,+ Inf)),则此函数将返回a。
- 如果您在此函数中传递NaN(例如Mod(a,NaN)),则此函数将返回NaN。
例1:
// Golang程序,演示如何
// 找到指定数字的模数
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 使用Mod()函数找到给定数字的模数
res_1 := math.Mod(60, 5)
res_2 := math.Mod(-100, 100)
res_3 := math.Mod(45.6, 8.9)
res_4 := math.Mod(math.NaN(), 67)
res_5 := math.Mod(math.Inf(1), 67)
// 显示结果
fmt.Printf("Result 1: %.1f", res_1)
fmt.Printf("\nResult 2: %.1f", res_2)
fmt.Printf("\nResult 3: %.1f", res_3)
fmt.Printf("\nResult 4: %.1f", res_4)
fmt.Printf("\nResult 5: %.1f", res_5)
}
输出:
Result 1: 0.0
Result 2: -0.0
Result 3: 1.1
Result 4: NaN
Result 5: NaN
例2:
// Golang程序,演示如何
// 找到指定数字的模数
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 使用Mod()函数找到给定数字的模数
nvalue_1 := math.Mod(34, 6)
nvalue_2 := math.Mod(56.7, 3.4)
// 查找给定模数的总和
res := nvalue_1 + nvalue_2
fmt.Printf("%.2f + %.2f = %.2f",
nvalue_1, nvalue_2, res)
}
输出:
4.00 + 2.30 = 6.30