dongyi5425 2017-02-25 05:57
浏览 59
已采纳

big.NewInt匿名变量的怪异行为

In the code snippet below, I want to make a very simple calculation d = a + b + c; a, b, c = b, c, d. It iterates several times.

In the first try, I make an anonymous variable big.NewInt(0).Add(a, b) to get the result of a + b, then add it and c to get the final result of a + b + c. But from the second iteration, d.Add(big.NewInt(0).Add(a, b), c) changed the value of c, then b, then a, and of course, the final result is wrong.

However, the second try's method gave me the right answer. Can anyone tell me why, please?

package main

import (
    "fmt"
    "math/big"
)

func main() {
    // first try
    a := big.NewInt(1)
    b := big.NewInt(2)
    c := big.NewInt(3)
    d := big.NewInt(0)
    for i := 0; i < 5; i++ {
        // d = a + b + c
        d.Add(big.NewInt(0).Add(a, b), c)
        fmt.Println(a, b, c, d)
        // a <- b, b <- c, c <- d
        a, b, c = b, c, d
        fmt.Println(a, b, c, d)
    }
    fmt.Println(d)

    // second try
    a = big.NewInt(1)
    b = big.NewInt(2)
    c = big.NewInt(3)
    d = big.NewInt(0)
    for i := 0; i < 5; i++ {
        // d = a + b + c
        d = big.NewInt(0).Add(big.NewInt(0).Add(a, b), c)
        fmt.Println(a, b, c, d)
        // a <- b, b <- c, c <- d
        a, b, c = b, c, d
        fmt.Println(a, b, c, d)
    }

    fmt.Println(d)
}
  • 写回答

1条回答 默认 最新

  • dtlzdofl66441 2017-02-25 06:08
    关注

    math/big.NewInt returns a pointer to an Int, so after your first iteration, both c and d point to the same object. This means, in your second iteration, when you add something to d, the same change will be reflected in c. Then you copy c to b so b will also point to the same object, and on the next iteration b to a, so after your third iteration, all 4 variables point to the same Int.

    Your second loop works because you create a new Int for d each time, so every time you shift the pointers, a new Int (the one which was created for d) gets moved to c, then to b, then to a.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?