比较Go语言中的大整数不等式?

huangapple go评论77阅读模式
英文:

Comparing inequalities for Go bigInt?

问题

我正在尝试比较两个大整数。我查看了文档:https://pkg.go.dev/math/big#Int,但我没有看到不等号操作符,只看到了一个相等操作符(Cmp)。

我应该如何比较一个大整数a和一个大整数b?我应该将b从a中减去并比较符号吗?还是我漏掉了什么?例如:

c := (new.bigInt).Sub(a, b)
i := c.Sign()
if i < 0 {
    fmt.Println("a < b")
}

我觉得没有不等号操作符有点奇怪,而且关于这个问题的资料也不多,所以我觉得我可能做错了什么。

英文:

I am trying to compare two big ints. I'm looking at the docs: https://pkg.go.dev/math/big#Int and I don't see an inequality operator, but I do see an equality one (Cmp).

How am I meant to compare a big int a to a big int b?
Am I meant to subtract b from a and compare the sign? Or is there something I am missing? E.g.

c := (new.bigInt).Sub(a, b)
i := c.Sign()
if i &lt; 0 {
    fmt.Println(&quot;a &lt; b&quot;)
}

It seems a little odd to me there is not an inequality operator, nor much about this online so I think I am doing something wrong.

答案1

得分: 2

Cmp 返回:-1 如果 x < y,0 如果 x == y,+1 如果 x > y

Go Playground 示例

英文:

Cmp returns: -1 if x < y, 0 if x == y, +1 if x > y

Go Playground Example

huangapple
  • 本文由 发表于 2021年11月21日 20:23:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/70054487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定