亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
開心每一天1111 2023-07-31 16:33:05
在A Tour of Go 的Numeric Constants部分中,代碼是package mainimport "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 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

來自關于常量的 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)

游樂場輸出:


?10 : type =? ? ? int

0.1 : type =? float64


?x? : type =? ? ? int? value = 214748364

?y? : type =? float64? value = 2.147483648e+08

  • x是 anint因為 devisor10被解釋為 an?int。

  • y是 afloat64因為乘數0.1被解釋為 a?float64。

在游覽示例中,const 是1<<100,它太大而無法放入int(32 位),因此程序甚至無法編譯,因為該數字無法存儲到分配的內存類型中:100 位無法放入32 位int.


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號