duan89197 2015-07-11 04:45
浏览 211
已采纳

为什么必须将整数转换为float64才能进行匹配?

I have been playing around with Go and I ran into a (non?)feature of Go while running the following code:

a := 1     //int
b := 1.0   //float64

c := a/b   //should be float64

When I ran this I get the following run-time error:

invalid operation: a / b (mismatched types int and float64) 

I thought GoLang was supposed to be pretty good with type inference. Why should it be necessary for me to write:

c := float64(a)/b    //float64

In general, given two number types, c should be inferred to be the smallest type that contains both. I can't see this as being an oversight, so I am just trying to figure out why this behavior was decided upon. For readability reasons only? Or would my suggested behavior cause some kind of logical inconsistency in language or something?

  • 写回答

1条回答 默认 最新

  • dtihe8614 2015-07-11 04:55
    关注

    This is mentioned in the FAQ: Why does Go not provide implicit numeric conversions?

    The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?
    It also complicates the compiler.

    That is why you need:

    • either to do an explicit type conversion:

      c := float64(a)/b
      
    • or to use var float64

      var a, b float64
      a = 1     //float64
      b = 1.0   //float64
      c := a/b 
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答