doufu5401 2017-04-08 06:29
浏览 408
已采纳

如何在Go中使用大整数?

I need to perform operations, such as exponentiation and division, on large values of int64 in Go, but I have problems with overflow. I tried converting them to float64, but then I run into other problems. Here is what I tried.

I have an integer variable, which I had to cast into a float64 to use the handy math package (https://golang.org/pkg/math).

However, it doesn't cast correctly when the integer variable is too big. I'm assuming it's because the size is bigger than float64. ex:

fmt.Printf("%f",float64(111111111111111110)) //Outputs 111111111111111104.000000

I'm trying to use math.Mod, math.Pow10, and math.Log10. How would I be able to do the following logic, but with a large number shown above?

int(math.Mod(float64(123) / math.Pow10(1),10))) // Gets the second digit
  • 写回答

2条回答 默认 最新

  • doubei2340 2017-04-08 07:41
    关注

    The question is not really clear to me, but I assume you want to perform operations on large integers and were only using float64 as a try.

    In that case, the right tool is the math/big package. Here is how to use it to extract the nth decimal digit of an int64:

    // first digit is n=0
    func nthDigit(i int64, n int64) int64 {
        var quotient big.Int
        quotient.Exp(big.NewInt(10), big.NewInt(n), nil)
    
        bigI := big.NewInt(i)
        bigI.Div(bigI, &quotient)
    
        var result big.Int
        result.Mod(bigI, big.NewInt(10))
    
        return result.Int64()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘