嘿,我正在创建一个函数(除n),它应该在模函数和函数的帮助下计算一个数n中的除数
(if (= (divides n k) #f)
0
我不知道为什么,但代码不会将if语句求值为true或false。。它只是跳过它。而且我不确定0应该是正确的输出。我希望它跳过那个数字,而不计算它。
这是我的代码:
(define (divides a b) (= 0 (modulo b a)))
(define (divisors-upto n k)
(if (= (divides n k) #f)
0
(+ k (divisors-upto n (- k 1)))))
(define (divisors n) (divisors-upto n n))
(divisors 4) ;for example should produce the result 3
首先修复divides
过程,将参数反转为modulo
。它应该是这样的:
(define (divides a b)
(= 0 (modulo a b)))
上面测试了b
是否划分a
,这就是在divisors-upto
过程中使用它的方式。你也应该更换这个:
(= (divides n k) #f)
有了这个:
(equal? (divides n k) #f)
或者更好的是,这个:
(not (divides n k))
除此之外,这不是你之前发布的问题吗?我在那里告诉过你,你在递归中遗漏了一个案例,看看我之前在链接中的回答。
如果这不是同一个过程,那么我真的不确定你想做什么:在这个问题中,你说这个过程"应该计算一个数中的除数",但这不是这个过程所做的——你添加的是实际除数(过程中的k
参数),而不是除数。再说一遍,你会错过一个案例——如果当前的k
不是除数,会发生什么?递归会提前退出!试着对此做一点工作,填空:
(define (divisors-upto n k)
(cond ((zero? k)
<???>) ; how many divisors are there if k is zero?
((not (divides n k))
<???>) ; if k is not a divisor of n, we must proceed without incrementing
(else ; if k is a divisor of n, by how many should the count be incremented?
(+ <???> (divisors-upto n (- k 1))))))