首页 > 其他 > 详细

3.3 四舍五入

时间:2018-03-22 01:17:48      阅读:196      评论:0      收藏:0      [点我收藏+]
package main

import (
    "fmt"
    "math"
)

var valA float64 = 3.55554444

func main() {

    // Bad assumption on rounding
    // the number by casting it to
    // integer.
    intVal := int(valA)
    fmt.Printf("Bad rounding by casting to int: %v\n", intVal)

    fRound := Round(valA)
    fmt.Printf("Rounding by custom function: %v\n", fRound)

}

// Round returns the nearest integer.
func Round(x float64) float64 {
    t := math.Trunc(x)
    if math.Abs(x-t) >= 0.5 {
        return t + math.Copysign(1, x)
    }
    return t
}

/*
Bad rounding by casting to int: 3
Rounding by custom function: 4

*/

3.3 四舍五入

原文:https://www.cnblogs.com/zrdpy/p/8620747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!