Understanding Division in Go
In Go, division is a mathematical operation used to calculate the quotient of two operands. However, performing division with untyped constants can lead to unexpected results.
Default Integer Operations
By default, division operations involving untyped constants result in integer values. For example, the expression fmt.Println(3/10) prints 0 because the operands are both untyped integer constants, and the operation follows integer division rules.
Floating-Point Results
To obtain floating-point division results, one of the operands must be a floating-point constant. This can be achieved by using the . decimal point syntax, as in 3.0 / 10.0 or 3 / 10.0. The resulting value will be an untyped floating-point constant (represented as float64).
Type Conversion
If you want to convert an untyped integer constant to a float64 variable, you can use the float64() conversion function. For example, fmt.Println(float64(3) / 10) will print 0.3. Alternatively, you can cast the integer constant to a float64 directly, as in fmt.Println(3 / float64(10)).
Note: Untyped numeric literals like 10.0 and 3.0 are not float64 constants. They still result in integer division if used with untyped integer constants.
Summary
In Go, division between untyped constants results in integer values. To obtain floating-point results, at least one operand must be a floating-point constant or an untyped constant converted to a float64.
The above is the detailed content of How Does Go Handle Division with Untyped Constants?. For more information, please follow other related articles on the PHP Chinese website!