if else condition with math/big

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

if else condition with math/big

问题

我正在尝试对大数进行比较,但只能得到字符串值。那么如何对big.Int进行条件判断呢?以下是我尝试过的最接近的代码:

package main

import (
	"fmt"
	"math/big"
)

func main() {

	dirtyVal := "9446744073709551615"
	dv := big.NewInt(0)
	dv.SetString(dirtyVal, 10)
	userVal := dv.String()

	maxVal := "18446744073709551615"
	mv := big.NewInt(0)
	mv.SetString(maxVal, 10)
	// maxValue := mv.String()

	if userVal > maxVal {
		fmt.Println("True")
	} else {
		fmt.Println("False")
	}

}

请注意,我只翻译了代码部分,其他内容不做翻译。

英文:

I'm trying to do comparisons on big numbers but can only get a the string value.
So how do you do a condition on a big.Int. Below is the closest to what I have tried.

package main

import (
	"fmt"
	"math/big"
)

func main() {

	dirtyVal := "9446744073709551615"
	dv := big.NewInt(0)
	dv.SetString(dirtyVal, 10)
	userVal := dv.String()

	maxVal := "18446744073709551615"
	mv := big.NewInt(0)
	mv.SetString(maxVal, 10)
	// maxValue := mv.String()

	if userVal > maxVal {
		fmt.Println("True")
	} else {
		fmt.Println("False")
	}

}

答案1

得分: 2

你可以使用func (*Int) Cmp来比较两个big.Int类型的值。http://golang.org/pkg/math/big/#Int.Cmp

if dv.Cmp(mv) > 0 {
    fmt.Println("True")
} else {
    fmt.Println("False")
}
英文:

You can use func (*Int) Cmp to compare two big.Int http://golang.org/pkg/math/big/#Int.Cmp

if dv.Cmp(mv)>0 {
    fmt.Println("True")
} else {
    fmt.Println("False")
}

huangapple
  • 本文由 发表于 2014年4月15日 00:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/23065010.html
匿名

发表评论

匿名网友

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

确定