大量打印 [英] Go print large number

查看:74
本文介绍了大量打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写Go Lang教程,确切地说是数值常数".示例代码以以下语句开头:

I am currently doing the Go Lang tutorial, "Numeric Constants" to be precise. The example code starts with the following statement:

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other words, the binary number that is 1 followed by 100 zeroes.
    Big = 1 << 100
    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    Small = Big >> 99
)

常量Big显然很大,我正在尝试打印它及其类型,如下所示:

The constant Big is obviously huge, and I am trying to print it and its type, like this:

fmt.Printf("%T", Big)
fmt.Println(Big)

但是,两行都出现以下错误:

However, I get the following error for both lines:

#命令行参数./compile26.go:19:常量1267650600228229401496703205376溢出int

# command-line-arguments ./compile26.go:19: constant 1267650600228229401496703205376 overflows int

我会尝试将Big强制转换为其他类型,例如uint64,它会因相同的错误而溢出,或者只是将其转换为字符串,但是在尝试Big.String()时,出现以下错误:

I would try casting Big to some other type, such as uint64, which it overflowed with the same error, or just convert it to a string, but when trying Big.String() I get the following error:

Big.String未定义(int类型没有字段或方法String)

Big.String undefined (type int has no field or method String)

看来它的类型是int,但是我无法打印它或将其强制转换为任何东西,并且它溢出了所有方法.我如何处理这个数字/对象以及如何打印它?

It appears that its type is int, yet I can't print it or cast it to anything and it overflows all methods. What do I do with this number/object and how do I print it?

推荐答案

该值大于任何64位数字类型可以容纳的值,因此您无法直接对其进行操作.

That value is larger than any 64 bit numeric type can hold, so you have no way of manipulating it directly.

如果您需要编写只能用math/big程序包处理的数字常量,则需要以程序包可以使用的格式序列化存储它.最简单的方法可能是使用以10为底的字符串:

If you need to write a numeric constant that can only be manipulated with the math/big package, you need to store it serialized in a format that package can consume. Easiest way is probably to use a base 10 string:

https://play.golang.org/p/Mzwox3I2SL

bigNum := "1267650600228229401496703205376"
b, ok := big.NewInt(0).SetString(bigNum, 10)
fmt.Println(ok, b)
// true 1267650600228229401496703205376

这篇关于大量打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆