go big.Float的大坑,求解释

package main

import (
    "fmt"
    "math/big"
)

func ToBigFloat(str string) big.Float {
    f, _, _ := big.ParseFloat(str, 10, 256, big.ToNearestEven)
    return *f
}

func main()  {
    a1 := ToBigFloat("100")
    a2 := a1

    fmt.Printf("a1 = %s\n", a1.String())
    fmt.Printf("a2 = %s\n", a2.String())

    a1.Add(&a1, big.NewFloat(10))

    fmt.Printf("a1 = %s\n", a1.String())
    fmt.Printf("a2 = %s\n", a2.String())
}

运行结果是

a1 = 100
a2 = 100
a1 = 110
a2 = 0

有人能解释一下吗

已邀请:

kevin - 杭州云柚科技

赞同来自:

因为你的用法不对...

package main

import (
    "fmt"
    "math/big"
)

func ToBigFloat(str string) *big.Float {
    f, _, _ := big.ParseFloat(str, 10, 256, big.ToNearestEven)
    return f
}

func main()  {
    a1 := ToBigFloat("100")
    a2 := big.NewFloat(0)
    a2.Copy(a1)

    fmt.Printf("a1 = %s\n", a1.String())
    fmt.Printf("a2 = %s\n", a2.String())

    a1.Add(a1, big.NewFloat(10))

    fmt.Printf("a1 = %s\n", a1.String())
    fmt.Printf("a2 = %s\n", a2.String())
}

h12 - https://h12.io/about

赞同来自:

我觉得这个问题很有意思,不能简单说楼主用法不对就糊弄过去了。为什么big.Float从a1到a2复制了一份,最后改了a1还把a2也改了?更有意思的是为什么a1改了以后是110,a2却变成0了。要解答这个问题,我把源代码改了一下,自己看打印结果:

package main

import (
    "fmt"
    "math/big"
)

func ToBigFloat(str string) big.Float {
    f, _, _ := big.ParseFloat(str, 10, 256, big.ToNearestEven)
    return *f
}

func main()  {
    a1 := ToBigFloat("100")
    a2 := a1

    fmt.Printf("a1 = %s = %#v\n", a1.String(), a1)
    fmt.Printf("a2 = %s = %#v\n", a2.String(), a2)

    a1.Add(&a1, big.NewFloat(10))

    fmt.Printf("a1 = %s = %#v\n", a1.String(), a1)
    fmt.Printf("a2 = %3s = %#v\n", a2.String(), a2)
}

要回复问题请先登录注册