How to perform division in Go

后端 未结 2 1917
忘掉有多难
忘掉有多难 2020-12-29 01:07

I am trying to perform a simple division in Go.

fmt.Println(3/10)

This prints 0 instead of 0.3. This is kind of weird. Could someone please

相关标签:
2条回答
  • 2020-12-29 01:18

    The expression 3 / 10 is an untyped constant expression. The specification says this about constant expressions

    if the operands of a binary operation are different kinds of untyped constants, the operation and, for non-boolean operations, the result use the kind that appears later in this list: integer, rune, floating-point, complex.

    Because 3 and 10 are untyped integer constants, the value of the expression is an untyped integer (0 in this case).

    One of the operands must be a floating-point constant for the result to a floating-point constant. The following expressions evaluate to the untyped floating-point constant 0.3:

    3.0 / 10.0
    3.0 / 10
    3 / 10.0
    

    It's also possible to use typed constants. The following expressions evaluate to the float64 constant 0.3:

    float64(3) / float64(10)
    float64(3) / 10
    3 / float64(10)
    

    Printing any of the above expressions will print 0.3. For example, fmt.Println(3.0 / 10) prints 0.3.

    0 讨论(0)
  • 2020-12-29 01:27

    As mentioned by @Cerise and per the spec

    Arithmetic operators apply to numeric values and yield a result of the same type as the first operand.

    In this case only the first operand needs to be a floating point.

    fmt.Println(3.0/10)
    fmt.Println(float64(3)/10)
    // 0.3 0.3
    

    Example

    0 讨论(0)
提交回复
热议问题