【问题标题】:Division with returning quotient and remainder带返回商和余数的除法
【发布时间】:2021-09-28 14:32:57
【问题描述】:

我尝试从 Python 迁移到 Golang。我目前正在研究一些数学运算,并想知道如何获得除法结果的商和余数。我将在下面分享一个等效的 Python 代码。

hours, remainder = divmod(5566, 3600)
minutes, seconds = divmod(remainder, 60)
print('%s:%s' % (minutes, seconds))
# 32:46

以上将是我的目标。谢谢。

【问题讨论】:

    标签: go


    【解决方案1】:

    整数除法加模数完成此操作。

    func divmod(numerator, denominator int64) (quotient, remainder int64) {
        quotient = numerator / denominator // integer division, decimals are truncated
        remainder = numerator % denominator
        return
    }
    

    https://play.golang.org/p/rimqraYE2B

    编辑:定义

    ,在整数除法的上下文中,是分子进入分母的整数次。也就是说,它等同于十进制语句:FLOOR(n/d)

    Modulo 为您提供了这种除法的余数。分子和分母的模数总是介于 0 和 d-1 之间(其中 d 是分母)

    【讨论】:

    • 您的解决方案非常清晰。没有像 Python 这样的内置工具让我很苦恼。
    【解决方案2】:

    如果你想要单线,

    quotient, remainder := numerator/denominator, numerator%denominator
    

    【讨论】:

      【解决方案3】:

      如果您有 32 位数字,则可以使用以下之一:

      package main
      import "math/bits"
      
      func main() {
         { // example 1
            var n uint = 4294967295
            q, r := bits.Div(0, n, 2)
            println(q == n / 2, r == 1)
         }
         { // example 2
            var n uint32 = 4294967295
            q, r := bits.Div32(0, n, 2)
            println(q == n / 2, r == 1)
         }
      }
      

      如果你有一个 64 位的数字,你可以这样做:

      package main
      import "math/bits"
      
      func main() {
         var n uint64 = 18446744073709551615
         q, r := bits.Div64(0, n, 2)
         println(q == n / 2, r == 1)
      }
      

      如果你有大于 64 位的东西,你可以这样做:

      package main
      import "math/bits"
      
      func main() {
         q, r := bits.Div64(1, 0, 2)
         println(q == 9223372036854775808, r == 0)
      }
      

      【讨论】:

        【解决方案4】:

        我做了这个功能,也许这就是你要找的。​​p>

        //QuotientAndRemainderF32 Computes the integer quotient and the remainder of the inputs. This function rounds floor(x/y) to the nearest integer towards -inf.
        func QuotientAndRemainderF32(x, y float32) (Remainder, Quotient float32) {
            Quotient = float32(math.Floor(float64(x / y)))
            Remainder = x - y*Quotient
            return Remainder, Quotient
        }
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 2011-08-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        • 2018-12-07
        • 2016-03-09
        • 1970-01-01
        • 2021-12-21
        相关资源
        最近更新 更多