Hi I am new to Go programing language.
I am learning from http://www.golang-book.com/
In chapter 4, under Exercises, there is a question on converting from Fahrenheit to Centigrade.
I coded up the answer as follows
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)
}
The output was as follows
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
My question is with outpu2 and outpu4. The parenthesizes are correct but how or why does it print -0.
Could anyone please explain
Quite simply, the expression
(5/9)is evaluated as(int(5)/int(9))which equals0. Try(5./9)And to clarify why this is happening, it deals with the order in which the expression variable’s types are determined.
I would guess that b/c
(5/9)exists without regards toinputin case 2 and 4 above, the compiler interprets them asintand simply replaces the expression with 0, at which point then the zero is considered dependent on input and thus takes on the typefloat64before final compilation.Generally speaking, Go does not convert numeric types for you, so this is the only explanation that would make sense to me.