2017-04-08 06:29
浏览 306


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 (

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

图片转代码服务由CSDN问答提供 功能建议

我需要对Go中int64的较大值执行求幂和除法操作,但是我遇到了问题 有溢出。 我尝试将它们转换为float64,但随后遇到其他问题。 这是我尝试的方法。

我有一个整数变量,必须将其转换为float64才能使用方便的数学包( )。

但是,当 整数变量太大。 我假设这是因为大小大于float64。 例如:


我正在尝试使用math.Mod,math.Pow10和math.Log10。 我如何能够执行以下逻辑,但是上面显示了很多数字?

  int(math.Mod(float64(123)/ math.Pow10(1))  ,10)))//获取第二个数字
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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()
    打赏 评论
  • douya7121 2017-04-08 07:57

    You can try to convert the int to string, and then fetch the digits in the converted string,

    // n >= 1
    func NthDigit(num int, n int) int {
        return int(strconv.Itoa(num)[n-1]) - int('0')
    打赏 评论

相关推荐 更多相似问题