我们在编程中经常需要对两个浮点型比较大小,下面我就来分享一段这样的代码,同时也展示了Go语言函数式编程的独特魅力:
import (
"fmt"
"math"
)
func main() {
// 设置精确度为0.00001
var a Accuracy = func() float64 { return 0.00001 }
fmt.Println(a.Equal(0.11111222, 0.11111222233333)) //打印结果为:true
}
type Accuracy func() float64
func (this Accuracy) Equal(a, b float64) bool {
return math.Abs(a-b) < this()
}
func (this Accuracy) Greater(a, b float64) bool {
return math.Max(a, b) == a && math.Abs(a-b) > this()
}
func (this Accuracy) Smaller(a, b float64) bool {
return math.Max(a, b) == b && math.Abs(a-b) > this()
}
func (this Accuracy) GreaterOrEqual(a, b float64) bool {
return math.Max(a, b) == a || math.Abs(a-b) < this()
}
func (this Accuracy) SmallerOrEqual(a, b float64) bool {
return math.Max(a, b) == b || math.Abs(a-b) < this()
}
有疑问加站长微信联系(非本文作者)