帮助!我正在尝试编写一个函数,它取两个输入中和之间所有数字的总和。
到目前为止,我有,
(define (sum-between x y)
(cond
[(= x y) x]
[((- x y) 0) 0]
[else (+ (+ x y) (sum-between (sub1 x) (sub1 y)))]))
这应该返回:
(check-expect (sum-between 0 2) 3)
(check-expect (sum-between -1 1) 0)
(check-expect (sum-between 7 7) 7)
(check-expect (sum-between 1 10) 55)
我不确定如何调用递归情况,因此它不会在无限循环中运行。有什么建议?谢谢!
答案 0 :(得分:0)
使用内置程序怎么样?这更容易:
(define (sum-between x y)
(apply + (range x (add1 y))))
但我想你想从头开始实现这个。这里的主要思想是其中一个值必须越来越接近另一个,你的错误是你正在递减它们的两个。试试这个:
(define (sum-between x y)
(cond
[(= x y) x]
[else (+ x (sum-between (add1 x) y))]))
答案 1 :(得分:0)
for / sum也可以在这里使用:
(define (sum-between x y)
(for/sum ((i (in-range x (add1 y))))
i))
(sum-between 0 2)
(sum-between -1 1)
(sum-between 7 7)
(sum-between 1 10)
输出:
3
0
7
55