dongshenjie3055 2012-11-22 02:45
浏览 38
已采纳

学习围棋—范围

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

  • 写回答

2条回答 默认 最新

  • drxdai15012937753 2012-11-22 03:10
    关注

    Quite simply, the expression (5/9) is evaluated as (int(5)/int(9)) which equals 0. 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 to input in case 2 and 4 above, the compiler interprets them as int and simply replaces the expression with 0, at which point then the zero is considered dependent on input and thus takes on the type float64 before final compilation.

    Generally speaking, Go does not convert numeric types for you, so this is the only explanation that would make sense to me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟