dqdfpmmi022763 2017-10-15 05:57
浏览 13
已采纳

大整数给我错误的平等结果

For some reason I'm getting the wrong result from big int when I test the equality even though the mod result is actually correct! For example, I would like to calculate 2015%2 which results in 1.

When I use big int, I get false when I do this:

fmt.Println((test.Mod(big.NewInt(2015),big.NewInt(2)))==big.NewInt(1))

However, when I use regular int, I get true (which is the correct thing anyway):

fmt.Println(2015%2==1)

Am I supposed to do the equality differently when using big int?

  • 写回答

2条回答 默认 最新

  • dsfgds4215 2017-10-15 06:27
    关注

    Package big

    import "math/big"
    

    func NewInt

    func NewInt(x int64) *Int
    

    NewInt allocates and returns a new Int set to x.

    func (*Int) Cmp

    func (x *Int) Cmp(y *Int) (r int)
    

    Cmp compares x and y and returns:

    -1 if x <  y
     0 if x == y
    +1 if x >  y
    

    The variables a and b are pointers: *big.Int. Use the Cmp method to compare values. For example,

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func main() {
        a := big.NewInt(42)
        fmt.Printf("a: %[1]T %[1]p %[1]v
    ", a)
        b := big.NewInt(42)
        fmt.Printf("b: %[1]T %[1]p %[1]v
    ", b)
        fmt.Println("pointers:", a == b)        // compare pointers
        fmt.Println("values:  ", a.Cmp(b) == 0) // compare values
    
        fmt.Println()
        test := new(big.Int)
        fmt.Println((test.Mod(big.NewInt(2015), big.NewInt(2))).Cmp(big.NewInt(1)) == 0)
    }
    

    Playground: https://play.golang.org/p/TH6UzceZ4y

    Output:

    a: *big.Int 0x1040a0c0 42
    b: *big.Int 0x1040a0d0 42
    pointers: false
    values:   true
    
    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 阿里云python代码求解
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路