Home > Backend Development > Golang > Why Does Go's Division Operation (/) Sometimes Return 0 Instead of a Decimal?

Why Does Go's Division Operation (/) Sometimes Return 0 Instead of a Decimal?

DDD
Release: 2024-12-11 15:17:09
Original
328 people have browsed it

Why Does Go's Division Operation (/) Sometimes Return 0 Instead of a Decimal?

Division Operation in Go

In Go, the division operation (/) is performed differently depending on the types of its operands. To understand why the expression fmt.Println(3 / 10) results in 0 instead of 0.3, let's delve into the type system of Go.

The operands in this expression are untyped integer constants, and according to the Go language specification, the result of arithmetic operations with untyped constants is determined by the order in which the types appear. Integer constants precede floating-point constants, so the expression is evaluated as an integer division, resulting in 0.

To obtain a floating-point result, at least one of the operands must be a floating-point constant. To achieve this, one can write 3.0 / 10.0, 3.0 / 10, or 3 / 10.0. The first two expressions use untyped floating-point constants, while the last expression converts the integer constant 3 to a float64.

Additionally, when one operand has an untyped constant and the other is a typed operand, the type of the expression is determined by the typed operand. Hence, var i3 = 3 and var i10 = 10 can be converted to float64 using fmt.Println(float64(i3) / float64(i10)).

Note that numeric literals like 10.0 are untyped floating-point constants, and expressions like i3 / 10.0 and 3.0 / i10 would still evaluate to integer division because of the typed operand (i3 and i10) determining the result type.

The above is the detailed content of Why Does Go's Division Operation (/) Sometimes Return 0 Instead of a Decimal?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template