How can I make division be a float in 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 the command line arguments -a 3 and -b 2, the output is: %!f(int=1)

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

+7
floating-point-conversion command-line-arguments go
source share
3 answers

There are no implicit ticks for variables in Go , so you should convert to float :

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

or

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

Depending on what you want. Also check out float64 - if it floats on your boat.

+10
source share

You must first convert the types to float.

In general, if you have some non-floating numeric types (for example, int s) a and b , to get float division you use float32(a)/ float32(b) (or float64 as it may be). This applies to any other digital type if you want to treat float as integers or integers, since complex numbers convert 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 performed, but the result is float, then the hidden result is, as in float32(a/b) . In this case, if a is 3 and b is 2, then float32(a/b) will get 1.0.

+3
source share

well, you have to give the result of division as a float

-3
source share

All Articles