【问题标题】:Go print large number去打印大号
【发布时间】:2016-10-10 21:23:37
【问题描述】:

我目前正在学习 Go Lang 教程,确切地说是“数字常量”。示例代码以以下语句开头:

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 显然很大,我正在尝试打印它及其类型,如下所示:

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

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

# command-line-arguments ./compile26.go:19: 常量 1267650600228229401496703205376 溢出 int

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

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

它的类型似乎是int,但我不能打印它或将它转换为任何东西,它会溢出所有方法。我该如何处理这个数字/对象以及如何打印它?

【问题讨论】:

  • Go 中的 const 是 not 正常变量,恰好是 const,它们是不同的。 const 的概念仅在编译期间存在,const 具有任意(几乎)精度,并且大小和算术是可能的。当 使用 一个 const 时,它会被转换为“正确的”类型。这种转换可能会失败,就像您的程序格式错误一样。没有(直接、简单)的方式来打印Big
  • @Volker @arik 如果您将 const 显式键入为 float64 或 complex128,您似乎可以打印它。那么,Big 的值作为 float64 是否不同于隐式类型 Big 的值,后者在使用时会在运行时转换为正确的类型? const Big float64 = 1 &lt;&lt; 100 fmt.Printf("Type of Big is: %T, Value of Big is %v", Big, Big) 这打印“Big 的类型是:float64,Big 的值是 1.2676506002282294e+30”

标签: go biginteger integer-overflow


【解决方案1】:

该值比任何 64 位数字类型都大,因此您无法直接操作它。

如果您需要编写一个只能使用math/big 包操作的数字常量,则需要以包可以使用的格式将其序列化存储。最简单的方法可能是使用以 10 为底的字符串:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2011-10-18
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多