我有一個比較兩個數字的簡單 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 關注
- 198 瀏覽
添加回答
舉報
0/150
提交
取消