登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-26 09:09:33 436浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何修复“(1

问题内容

a tour of 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 溢出 int, 他们之间有什么区别。


解决方案


摘自 go 博客 constants

数字常量存在于任意精度的数字空间中;他们 只是普通数字。但是当它们被分配给一个变量时 值必须能够适合目的地。

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

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

今天关于《如何修复“(1

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>