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

如何在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?

图片转代码服务由CSDN问答提供 功能建议

我有以下代码段:

  package main \  n 
import(“ fmt”;“ flag”)
 
func main(){
 var a = flag.Int(“ a”,0,“ divident”)
 var b = flag.Int(“ b  “,1,”除数“)
标志。Parse()
 
 fmt.Printf(”%f“,* a / * b)
} 
   
 \  n 

对于-a 3和-b 2命令行参数,输出为:%!f(int = 1)

什么是最好的 /强制该除法为浮点数的最优雅方法?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 打赏 评论

相关推荐 更多相似问题