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

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

學習圍棋—范圍

學習圍棋—范圍

Go
開滿天機 2021-05-14 18:19:12
嗨,我是Go編程語言的新手。我正在從http://www.golang-book.com/學習在第4章的練習中,有一個關于從華氏溫度轉換為攝氏度的問題。我將答案編碼如下    package mainimport "fmt"func main(){    fmt.Println("Enter temperature in Farentheit ");    var input float64    fmt.Scanf("%f",&input)    var outpu1 float64 = ( ( (input-32)* (5) ) /9)    var outpu2 float64=  (input-32) * (5/9)    var outpu3 float64= (input -32) * 5/9    var outpu4 float64=  ( (input-32) * (5/9) )     fmt.Println("the temperature in Centigrade is ",outpu1)    fmt.Println("the temperature in Centigrade is ",outpu2)    fmt.Println("the temperature in Centigrade is ",outpu3)    fmt.Println("the temperature in Centigrade is ",outpu4) }輸出如下sreeprasad:projectsInGo sreeprasad$ go run convertFarentheitToCentigrade.go Enter temperature in Farentheit 12.234234the temperature in Centigrade is  -10.980981111111111the temperature in Centigrade is  -0the temperature in Centigrade is  -10.980981111111111the temperature in Centigrade is  -0我的問題是關于outpu2和outpu4。括號是正確的,但是它如何或為什么顯示-0。誰能解釋一下
查看完整描述

2 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

很簡單,該表達式(5/9)被評估為(int(5)/int(9))equals 0。嘗試(5./9)

為了弄清楚為什么會發生這種情況,它處理了確定表達式變量類型的順序。

我猜想b / c的(5/9)存在不考慮input上述情況2和4,編譯器將它們解釋為,int并簡單地將表達式替換為0,這時零被認為取決于輸入,因此float64在最終之前采用類型匯編。

一般來說,Go不會為您轉換數字類型,因此這是唯一對我有意義的解釋。


查看完整回答
反對 回復 2021-05-24
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

圍棋語言規格說明float32float64簽署浮動遵循IEEE-754標準的數字。以下是引自維基百科的文字-簽名為零

IEEE 754浮點算術標準(目前大多數支持浮點數的計算機和編程語言都在使用)要求+0和?0。零可被視為擴展實數線的變體,因此1 / ?0 =-∞和1 / + 0 = +∞,僅對±0 /±0和±∞/±∞未定義以零除。

顯然,input當afloat64加上負32時,它變成另一個float64為負數。5/9評估為0。負數float64計時0-0。

有趣的是,如果您將input整數替換為,例如1,則會得到0而不是-0。似乎在Go中,浮點數同時具有+0-0,而整數則沒有。

編輯: PhiLho在注釋中解釋了為什么整數不具有浮點數的原因:標準化的浮點數具有+ 0,-0,NaN,+ Infinity和-Infinity的特殊表示形式,而您無法保留一些位組合整數具有這樣的含義。


查看完整回答
反對 回復 2021-05-24
  • 2 回答
  • 0 關注
  • 282 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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