如果我将int数存储到一个结构中,然后将它们应用于它们,那恰好发生在我身上。精度会丢失。
func main() {
var x = 94911151
var y = 94911150
// If we use the value to calculate division directly, it would be fine
var result1 = float64(94911151)/94911150
var result2 = float64(x)/float64(y)
fmt.Println(result1, result2)
// If we pass the values directly as parameter into a function and then apply division, it would be fine
getParas(x,y)
// If we pass the values into a stuct, and then retrieve the value from struct, then apply division, the precision would be lost.
getLinearParas(Point{x,y},Point{0,0})
}
func getParas(a int, b int){
diffX := a -0
diffY := b-0
c:= float64(diffX) / float64(diffY)
fmt.Println(c)
}
type Point struct{
X int
Y int
}
func getLinearParas(point1 Point, point2 Point) {
diffX := point1.X - point2.X
diffY := point1.Y - point2.Y
a := float64(diffX) / float64(diffY)
fmt.Printf("diffY: %d; diffX:%d ; a:%f \n", diffY, diffX, a)
}
与代码一样,如果我将int值放入结构中,稍后对它们应用除法。精度会以某种方式丢失。 运行上面代码的结果是
1.00000001053617 1.00000001053617
1.00000001053617
diffY: 94911150; diffX:94911151 ; a:1.000000
或者你可以在游乐场自己尝试一下 https://play.golang.org/p/IDS18rfv9e6
有人可以解释为什么会这样吗?以及如何避免这种损失? 非常感谢你。
答案 0 :(得分:3)
将格式字符串中的%f
更改为%v
或%g
或%.14f
。 fmt.Println
打印相当于%v
,%v
的内容,因为float64被视为%g
。默认情况下,%f
打印带有6位有效数字的值,%g
使用“唯一标识该值所需的最小位数”。