首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >学习Go --范围

学习Go --范围
EN

Stack Overflow用户
提问于 2012-11-22 10:45:40
回答 2查看 248关注 0票数 3

嗨,我是编程语言的新手。

我正在向http://www.golang-book.com/学习

在第四章的练习中,有一个关于从华氏温度转换为摄氏度的问题。

我对答案进行了如下编码

代码语言:javascript
复制
    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) 
}

输出如下所示

代码语言:javascript
复制
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。

有人能解释一下吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 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不会为你转换数值类型,所以这是对我唯一有意义的解释。

票数 7
EN

Stack Overflow用户

发布于 2012-11-22 11:14:34

Go language Spec表示float32float64是符合IEEE754标准的有符号浮点数。以下文本引用自Wikipedia - Signed zero

浮点运算的IEEE754标准(目前由大多数计算机和支持浮点数的编程语言使用)需要+0和−0。零可以被视为扩展实数行的变体,使得1/−0 =−∞和1/+0 = +∞,除以零仅对于±0/±0和±∞/±∞是未定义的。

显然,作为float64input,当应用负32时,会变成另一个负float645/9的计算结果为0。由0计时的负float64-0

有趣的是,如果你用一个整数替换input,比如1,你会得到0而不是-0。似乎在Go中,浮点数同时有+0-0,但整数没有。

编辑: PhiLho在评论中解释了为什么浮点数有这样的东西,而整数没有:规范化的浮点数有+0,-0,NaN,+无穷和-Infinity的特殊表示,而你不能保留整数的一些位组合来具有这样的含义。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13505202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档