如何修复'(1 << 100)* 0.1和(1 << 100)/ 10'

时间:2019-10-31 02:25:04

标签: go

漫游之旅数字常量部分中,代码为

package main

import "fmt"

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
)

func needInt(x int) int { return x*10 + 1 }

func needFloat(x float64) float64 { return x * 0.1 }

func main() {
    fmt.Println(needInt(Small))
    fmt.Println(needFloat(Small))
    fmt.Println(needFloat(Big))

    fmt.Println(Big * 0.1) //one
    fmt.Println(Big / 10)  //two
}

fmt.Println(Big*0.1)输出1.2676506002282295e+29, 但是fmt.Println(Big / 10)抛出错误:constant 126765060022822940149670320537 overflows int, 他们之间有什么区别。

1 个答案:

答案 0 :(得分:0)

来自constants上的Go博客:

  

数字常量位于任意精度的数字空间中;他们   只是常规数字。但是,当将它们分配给变量时,   值必须能够适合目标。

一个例子可以使这一点更清楚:

const f = 1 << 31

x := f / 10  // what type is x?
y := f * 0.1 // what type is y?

fmt.Printf(" 10 : type = %8T\n", 10)    // int
fmt.Printf("0.1 : type = %8T\n\n", 0.1) // float64

fmt.Printf(" x  : type = %8T  value = %v\n", x, x)
fmt.Printf(" y  : type = %8T  value = %v\n", y, y)

Playground输出:

 10 : type =      int
0.1 : type =  float64

 x  : type =      int  value = 214748364
 y  : type =  float64  value = 2.147483648e+08

  • xint,因为除数10被解释为int
  • yfloat64,因为乘法器0.1被解释为float64

在巡回示例中,const为1<<100,它太大而无法容纳int(32位),因此该程序将甚至无法编译,因为数字不能为存储在分配的内存类型中:100位将不适合32位int