我有一个比较两个数字的简单 if 语句。由于编译错误,我无法使用big.Int与零进行比较,因此我尝试转换为 int64 和 float32。问题是在调用Int64or之后float32(diff.Int64()),diff被转换为一个正数,我怀疑这是整数溢出的结果。如果有人能告诉我什么是准备diff与零比较的变量的安全方法,我将不胜感激。package mainimport ( "fmt" "math/big")func main() { var amount1 = &big.Int{} var amount2 = &big.Int{} amount1.SetString("465673065724131968098", 10) amount2.SetString("500000000000000000000", 10) diff := big.NewInt(0).Sub(amount1, amount2) fmt.Println(diff) // -34326934275868031902 << this is the correct number which should be compared to 0 fmt.Println(diff.Int64()) // 2566553871551071330 << this is what the if statement compares to 0 if diff.Int64() > 0 { fmt.Println(float64(diff.Int64()), "is bigger than 0") }}
1 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
用于Int.Cmp()
将它与另一个big.Int
值进行比较,一个代表0
。
例如:
zero := new(big.Int)
switch result := diff.Cmp(zero); result {
case -1:
fmt.Println(diff, "is less than", zero)
case 0:
fmt.Println(diff, "is", zero)
case 1:
fmt.Println(diff, "is greater than", zero)
}
这将输出:
-34326934275868031902 is less than 0
与特殊的 进行比较时0,您也可以使用Int.Sign()它返回 -1、0、+1,具体取决于与 的比较结果0。
switch sign := diff.Sign(); sign {
case -1:
fmt.Println(diff, "is negative")
case 0:
fmt.Println(diff, "is 0")
case 1:
fmt.Println(diff, "is positive")
}
这将输出:
-34326934275868031902 is negative
尝试Go Playground上的示例。
见相关:
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报
0/150
提交
取消