Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

well you should cast your division result as float

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top