Golang 找到指定数字的整数值
Go语言提供了基本常量和数学函数的内置支持,以通过math包执行操作。你可以使用math包提供的Trunc()函数来找到指定数字的整数值。因此,你需要在程序中使用import关键字添加一个math包,以访问Trunc()函数。
语法:
func Trunc(a float64) float64
- 如果你在这个函数中传递-Inf或+Inf,如Trunc(-Inf)或Trunc(+Inf),则这个函数将返回-Inf或+Inf。
- 如果你在这个函数中传递-0或+0,如Trunc(-0)或Trunc(+0),则这个函数将返回-0或+0。
- 如果你在这个函数中传递NaN,如Trunc(NaN),则这个函数将返回NaN。
示例1:
// Golang程序演示如何
// 获取给定数字的整数值
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 寻找整数
// 使用Trunc()函数
res_1 := math.Trunc(45.98)
res_2 := math.Trunc(-119.98)
res_3 := math.Trunc(math.Inf(-1))
res_4 := math.Trunc(math.NaN())
res_5 := math.Trunc(math.Pi)
// 显示结果
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)
fmt.Printf("\n结果 5: %.1f", res_5)
}
输出:
结果 1: 45.0
结果 2: -119.0
结果 3: -Inf
结果 4: NaN
结果 5: 3.0
示例2:
// Golang程序演示如何获得
// 给定数字的整数值
package main
import (
"fmt"
"math"
)
// 主函数
func main() {
// 寻找整数值
// 使用Trunc()函数
nvalue_1 := math.Trunc(59.89)
nvalue_2 := math.Trunc(-7.567)
// 给定数字的总和
res := nvalue_1 + nvalue_2
fmt.Printf("%.2f + %.2f = %.2f",
nvalue_1, nvalue_2, res)
}
输出:
59.00 + -7.00 = 52.00