嗨,我是Go编程语言的新手.
我正在学习http://www.golang-book.com/
在第4章的练习中,有一个关于从华氏温度转换为摄氏温度的问题.
我将答案编码如下
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)
}
Run Code Online (Sandbox Code Playgroud)
输出如下
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
Run Code Online (Sandbox Code Playgroud)
我的问题是outpu2和outpu4.括号是正确的,但它如何或为什么打印-0.
有人可以解释一下
很简单,表达式(5/9)被评估为(int(5)/int(9))等于0.尝试(5./9)
为了澄清为什么会发生这种情况,它会处理表达式变量类型的确定顺序.
我猜想b/c (5/9)存在而不考虑input上面的情况2和4,编译器将它们解释为int并简单地用0替换表达式,此时零被认为是依赖于输入,因此float64在最终之前采用类型汇编.
一般来说,Go不会为您转换数字类型,因此这是对我有意义的唯一解释.