douyu53265 2013-12-13 16:28
浏览 1780
已采纳

如何在Go中强制除法成为浮点数?

I have the following code snippet:

package main

import("fmt";"flag")

func main() {
    var a = flag.Int("a",0,"divident")
    var b = flag.Int("b",1,"divisor")
    flag.Parse()

    fmt.Printf("%f",*a / *b )
}

For -a 3 and -b 2 command line arguments, the output is: %!f(int=1)

What is the best / most elegant way to force this division to be floating point?

  • 写回答

3条回答 默认 最新

  • duanmei1536 2013-12-13 16:40
    关注

    There are no implicit type casts for variables in Go, so you must convert to float:

    fmt.Printf("%f", float32(a)/float32(b))
    

    or

    fmt.Printf("%f", float32(a/b))
    

    Depending upon what you want. Also check out float64 -- if that floats your boat.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • doubi7496 2013-12-13 16:33
    关注

    well you should cast your division result as float

    评论
  • douyuanliao8815 2013-12-13 16:34
    关注

    You have to convert the types to floats first.

    In general, if you have some non-float numeric types (such as ints) a and b, in order to get a float division you use float32(a)/ float32(b) (or float64 as the case may be). This applies to any other numeric type too, if you want to treat floats as integers or integers as complex numbers convert the operands. In this case, if a is 3 and b is 2, float32(a)/float32(b) will be 1.5.

    If you want integer division to be done, but the result to be a float, then covert the result as in float32(a/b). In this case, if a is 3 and b is 2, then float32(a/b) will get you 1.0.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 VB6.0中PICTUREBOX加载本地图片无法显示
  • ¥100 关于游戏app session获取的问题
  • ¥15 MYSQL数据库建表
  • ¥15 爬虫程序爬取TTGChina网站文章代码
  • ¥35 由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作。
  • ¥15 如何用下图方法在AMESim中搭建离心泵模型
  • ¥15 C#连接服务器,请求时报Ssl/Tsl未能建立安全通道
  • ¥15 xcode15build的c++ dylib在10.15上不兼容
  • ¥15 CPLD如何实现在线逻辑分析
  • ¥15 控制面板卸载无权限!!