由于整数溢出,使用 Int64() 转换后负 big.Int 变为正

我有一个比较两个数字的简单 if 语句。由于编译错误,我无法使用big.Int与零进行比较,因此我尝试转换为 int64 和 float32。问题是在调用Int64or之后float32(diff.Int64()),diff被转换为一个正数,我怀疑这是整数溢出的结果。如果有人能告诉我什么是准备diff与零比较的变量的安全方法,我将不胜感激。


package main

import (

    "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")

    }


}


慕森王
浏览 98回答 1
1回答

12345678_0001

用于Int.Cmp()将它与另一个big.Int值进行比较,一个代表0。例如:zero := new(big.Int)switch result := diff.Cmp(zero); result {case -1:&nbsp; &nbsp; fmt.Println(diff, "is less than", zero)case 0:&nbsp; &nbsp; fmt.Println(diff, "is", zero)case 1:&nbsp; &nbsp; 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:&nbsp; &nbsp; fmt.Println(diff, "is negative")case 0:&nbsp; &nbsp; fmt.Println(diff, "is 0")case 1:&nbsp; &nbsp; fmt.Println(diff, "is positive")}这将输出:-34326934275868031902 is negative尝试Go Playground上的示例。见相关:还有另一种测试 big.Int 是否为 0 的方法吗?
打开App,查看更多内容
随时随地看视频慕课网APP