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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度