Golang math.RoundToEven()函数的使用及示例

Golang math.RoundToEven()函数的使用及示例

Go语言提供了内置的支持来处理数字的基本常量和数学函数,通过使用math包,您可以使用RoundToEven()函数将给定的数字舍入到最近的偶整数。 因此,您需要使用import关键字将math包添加到您的程序中以访问RoundToEven()函数。

语法:

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

示例1:

//演示如何将给定数字舍入到最近的偶整数的Golang程序
  
package main
  
import (
    "fmt"
    "math"
)
  
//主函数
func main() {
  
    //使用RoundToEven()函数
    res_1 := math.RoundToEven(45.98)
    res_2 := math.RoundToEven(-119.98)
    res_3 := math.RoundToEven(math.Inf(-1))
    res_4 := math.RoundToEven(math.NaN())
    res_5 := math.RoundToEven(math.Inf(1))
  
    //显示结果
    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: 46.0
Result 2: -120.0
Result 3: -Inf
Result 4: NaN
Result 5: +Inf

示例2:

//演示如何将给定数字舍入到最近的偶整数的Golang程序
  
import (
    "fmt"
    "math"
)
  
//主函数
func main() {
  
    //使用RoundToEven()函数
    nvalue_1 := math.RoundToEven(59.89)
    nvalue_2 := math.RoundToEven(-7.567)
  
    //两个给定数字的和
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.2f + %.2f = %.2f",
            nvalue_1, nvalue_2, res)
  
} 

输出:

60.00 + -8.00 = 52.00

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程