Golang math.Round()的使用及示例

Golang math.Round()的使用及示例

Go语言通过math包提供了基本常量和数学函数的内置支持,以便对数字执行操作。您可以使用math包提供的 Round()函数 将给定数字四舍五入到最近的整数(朝向远离零的一侧)。因此,您需要在程序中添加一个math包,以使用import关键字访问Round()函数。

语法:

func Round(a float64) float64
  • 如果在此函数中传递-Inf或+Inf,如Round(-Inf)或Round(+Inf),则此函数将返回-Inf或+Inf。
  • 如果在此函数中传递-0或+0,如Round(-0)或Round(+0),则此函数将返回-0或+0。
  • 如果在此函数中传递NaN,如Round(NaN),则此函数将返回NaN。

示例1:

// Golang程序演示如何将给定数字舍入到最近的整数
// 使用Round()函数
package main
import (
    "fmt"
    "math"
)
// 主函数
func main() {
    // 找到给定数字的最近整数
    // 使用Round()函数
    res_1 := math.Round(36.98)
    res_2 := math.Round(-100.98)
    res_3 := math.Round(math.Inf(-1))
    res_4 := math.Round(math.NaN())
    res_5 := math.Round(math.Inf(1))

    // 显示结果
    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: 37.0
    结果2: -101.0
    结果3: -Inf
    结果4: NaN
    结果5: +Inf

示例2:

// Golang程序演示如何将给定数字舍入到最近的整数
// 使用Round()函数
package main
import (
    "fmt"
    "math"
)
// 主函数
func main() {
    // 找到给定数字的最近整数
    // 使用Round()函数
    nvalue_1 := math.Round(49.89)
    nvalue_2 := math.Round(-4.567)

    // 找到给定数字的总和
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.2f + %.2f = %.2f",
        nvalue_1, nvalue_2, res)
} 

输出:

    50.00 + -5.00 = 45.00

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程