Golang 查找给定数字的最大整数值
Go 语言通过 math 包提供内置支持来执行常数和数学函数的基本操作。您可以使用 math 包提供的 Floor() 函数查找小于或等于指定数字的最大整数值。因此,您需要使用 import 关键字在程序中添加 math 包以访问 Floor() 函数。
语法:
func Floor(y float64) float64
- 如果在此函数中传递 +Inf 或 -Inf,则此函数将返回 +Inf 或 -Inf。
- 如果在此函数中传递 +0 或 -0,则此函数将返回 +0 或 -0。
- 如果在此函数中传递 NaN,则此函数将返回 NaN。
示例 1:
// Golang 程序,用于查找 floor 值
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 查找小于或等于指定数字的最大整数值
// 使用 Floor() 函数
res_1 := math.Floor(4.7)
res_2 := math.Floor(-8.976)
res_3 := math.Floor(0.687997)
// 显示结果
fmt.Printf("Result 1: %.1f", res_1)
fmt.Printf("\nResult 2: %.1f", res_2)
fmt.Printf("\nResult 3: %.1f", res_3)
}
输出:
Result 1: 4.0
Result 2: -9.0
Result 3: 0.0
示例 2:
// Golang 程序,用于查找 floor 值
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 查找小于或等于指定数字的最大整数值
// 使用 Floor() 函数
nvalue_1 := 3.4556775
nvalue_2 := 23.564646
res := nvalue_1 + nvalue_2
fmt.Printf("%.5f + %.5f = %.5f",
nvalue_1, nvalue_2, res)
fmt.Println("\nGreatest integer value: ",
math.Floor(res))
}
输出:
3.45568 + 23.56465 = 27.02032
Greatest integer value: 27