duanhuo7441 2017-07-06 04:36
浏览 89
已采纳

与golang中的类型转换混淆

I recently tried to learn golang. But I got confused with this code from https://tour.golang.org/basics/13.

package main

import (
    "fmt"
    "math"
)

func main() {
    var x, y int = 3, 4
    var f float64 = math.Sqrt(float64(x*x + y*y))
    var z uint = uint(f)
    fmt.Println(x, y, z)
}

That one works well. Then I tried

var f = math.Sqrt(9 + 16)

which also works. But when I change it to var f = math.Sqrt(x*x + y*y) why is it not working? It says cannot use x * x + y * y (type int) as type float64 in argument to math.Sqrt

I have javascript background, and I somehow can't understand the code above.

  • 写回答

2条回答 默认 最新

  • dongtan7998 2017-07-06 04:50
    关注

    The math.Sqrt function signature:

    func Sqrt(x float64) float64
    

    requires that you pass float64

    In this case:

    var f float64 = math.Sqrt(float64(x*x + y*y))
    

    You are converting to float64 directly

    In this case:

    var f = math.Sqrt(x*x + y*y)
    

    you are passing an int, when float64 is required.

    In this case:

    var f = math.Sqrt(9 + 16)
    

    The compiler is able to infer the type, and pass float64 for you.

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

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题