2012-11-22 51 views
3

嗨,我是新來的編程語言。學習去 - 範圍

我從http://www.golang-book.com/

學習在第四章中,在練習中,對從轉換到華氏攝氏度的問題。

我編寫了答案如下

package main 

import "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.234234 
the temperature in Centigrade is -10.980981111111111 
the temperature in Centigrade is -0 
the temperature in Centigrade is -10.980981111111111 
the temperature in Centigrade is -0 

我的問題是與outpu2和outpu4。括號是正確的,但是如何或爲什麼打印-0。

任何人都可以請解釋

回答

7

很簡單,表達(5/9)被評價爲(int(5)/int(9))其等於0。嘗試(5./9)

爲了澄清爲什麼會發生這種情況,它處理表達式變量類型的確定順序。

我猜想,B/C (5/9)在殼體2而不考慮input存在和4的上方,則編譯器將它們解釋爲int和簡單地替換表達式與0,在該點,則零被認爲是依賴於輸入和因此在最終編譯之前採用float64類型。

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

3

Go language Spec表示float32float64是符合IEEE-754標準的有符號浮點數。下面的文本是Wikipedia - Signed zero報價:

的IEEE 754標準的浮點運算(目前使用的大多數計算機和支持浮點數的編程語言)既需要+0和-0。可以認爲零點是擴展實數行的一個變體,使得1/-0 =-∞和1/+ 0 = +∞,除以零僅在±0 /±0和±∞/±∞ 。

顯然,input,作爲float64,當施加負32,變成另一個float64且爲負。 5/9評估爲0。定時爲0的負float64-0

有趣的是,如果用整數替換input,例如1,您將獲得0而不是-0。看起來在Go中,浮動數字既有+0也有-0,但整數沒有。

編輯:PhiLho解釋這是什麼緣故評論爲什麼浮點數有這樣的事情,而整數別:標準化浮點數有+ 0,-0,NaN,則正無窮和負無窮大的特殊表示,而不能保留一些整數的位組合來表示這些含義。

+2

是的,標準化的浮點數有+0,-0,NaN,+ Infinity和-Infinity的特殊表示。你不能保留一些整數的組合來具有這樣的含義...... – PhiLho

+0

+1用於回答對問題的其他解釋。我甚至沒有注意到負號:) – dskinner

+0

@dskinner謝謝!負面信號引起了我的注意,因爲我也不知道原因。所以我做了一些研究:) –