亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

由于整數溢出,使用 Int64() 轉換后負 big.Int 變為正

由于整數溢出,使用 Int64() 轉換后負 big.Int 變為正

Go
慕森王 2023-01-03 11:27:24
我有一個比較兩個數字的簡單 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上的示例。

見相關:

還有另一種測試 big.Int 是否為 0 的方法嗎?


查看完整回答
反對 回復 2023-01-03
  • 1 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號