嗨,我是编程语言的新手。
我正在向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。
有人能解释一下吗?
发布于 2012-11-22 11:10:06
非常简单,表达式(5/9)的计算结果为等于0的(int(5)/int(9))。试试(5./9)
为了阐明为什么会发生这种情况,它处理了表达式变量的类型被确定的顺序。
我猜测b/c (5/9)的存在与input无关。在上面的情况2和4中,编译器将它们解释为int,并简单地将表达式替换为0,此时0被认为依赖于输入,因此在最终编译之前采用float64类型。
一般来说,Go不会为你转换数值类型,所以这是对我唯一有意义的解释。
发布于 2012-11-22 11:14:34
Go language Spec表示float32和float64是符合IEEE754标准的有符号浮点数。以下文本引用自Wikipedia - Signed zero
浮点运算的IEEE754标准(目前由大多数计算机和支持浮点数的编程语言使用)需要+0和−0。零可以被视为扩展实数行的变体,使得1/−0 =−∞和1/+0 = +∞,除以零仅对于±0/±0和±∞/±∞是未定义的。
显然,作为float64的input,当应用负32时,会变成另一个负float64。5/9的计算结果为0。由0计时的负float64是-0。
有趣的是,如果你用一个整数替换input,比如1,你会得到0而不是-0。似乎在Go中,浮点数同时有+0和-0,但整数没有。
编辑: PhiLho在评论中解释了为什么浮点数有这样的东西,而整数没有:规范化的浮点数有+0,-0,NaN,+无穷和-Infinity的特殊表示,而你不能保留整数的一些位组合来具有这样的含义。
https://stackoverflow.com/questions/13505202
复制相似问题