Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I force division to be floating point 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 -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?

like image 951
Croo Avatar asked Dec 13 '13 16:12

Croo


People also ask

How do you force floating-point division?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

Does division always return float?

In Python, the “//” operator works as a floor division for integer and float arguments. However, the division operator '/' returns always a float value.

How do you divide numbers in Golang?

Golang Division Operator takes two operands and returns the division of first operand by second operand. Both the operands provided to Division Operator should be of same datatype. Golang Division Operator applies to integers, floats, and complex values. Division Operator is also called Quotient Operator.

How do you float a division in Python?

In Python 3, "/" uniformly works as a float division operator. So, it always returns the float type: 10/3 returns 3.333333 instead of 3, 6/3 returns 2.0 instead of 2.


1 Answers

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.

like image 99
bishop Avatar answered Nov 06 '22 21:11

bishop