简体   繁体   English

楼层划分的递归函数

[英]recursive function for floor division

I am creating a recursive function that essentially operates floor division without using the ' // ' operator. 我正在创建一个递归函数,它基本上操作楼层划分而不使用'//'运算符。 I have figured out the function, but only when input n is positive and I am struggling to figure out how to operate the function when n < d. 我已经找到了函数,但只有当输入n是正数时我才会努力弄清楚当n <d时如何操作函数。 Any help is greatly appreciated, thanks! 非常感谢任何帮助,谢谢!

My current code: 我目前的代码:

def quotient( n , d ):

    if (n >= d):
        return quotient(n - d, d) + 1

    else: 
        return n

You can do it like that: 你可以这样做:

def quotient( n , d ):

    if (0<=n<d):
        return 0
    if (n >= d):
        return quotient(n - d, d) + 1
    if n<0:
        return quotient(n + d, d) - 1

If 0<=n<d the quotient is 0, this is the first if . 如果0<=n<d则商为0,这是第一个if If n is negative, we handle it in a similar fashion to the positive case, just switch the signs. 如果n为负数,我们会以与正数情况类似的方式处理它,只需切换符号即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM