Golang 找到两个数字的最小值
Go 语言提供了基本常量和数学函数的内置支持,可以使用 math 包执行数字操作。您可以使用 math 包提供的 Min() 函数在给定的两个数字中找到最小数字。因此,您需要使用 import 关键字将 math 包添加到程序中,以访问 Min() 函数。
语法:
func Min(a, b float64) float64
- 如果在此函数中传递 -Inf(例如 Min(-Inf, b) 或 Min(a, -Inf)),则此函数将返回 -Inf。
- 如果在此函数中传递 NaN(例如 Min(NaN, b) 或 Min(a, NaN)),则此函数将返回 NaN。
- 如果在此函数中传递 -0 或 +0(例如 Min(-0,-0) 或 Min(-0,+0) 或 Min(-0,-0)或 Min(+0,-0)),则此函数将返回 -0。
示例1:
// Golang示例程序,说明如何
// 查找最小数字
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 在给定的数字中查找最小数字
// 使用 Min() 函数
res_1 := math.Min(0, -0)
res_2 := math.Min(-100, 100)
res_3 := math.Min(45.6, 8.9)
res_4 := math.Min(math.NaN(), 67)
// 显示结果
fmt.Printf("结果1:%.1f", res_1)
fmt.Printf("\n结果2:%.1f", res_2)
fmt.Printf("\n结果3:%.1f", res_3)
fmt.Printf("\n结果4:%.1f", res_4)
}
输出:
结果1:0.0
结果2:-100.0
结果3:8.9
结果4:NaN
示例2:
// Golang示例程序,说明如何
// 查找最小数字
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 在给定的数字中查找最小数字
// 使用 Min() 函数
nvalue_1 := math.Min(34, 67)
nvalue_2 := math.Min(56.7, 90.8)
// 添加最小的数字
res := nvalue_1 + nvalue_2
fmt.Printf("%.2f + %.2f = %.2f",
nvalue_1, nvalue_2, res)
}
输出:
34.00 + 56.70 = 90.70