3 回答
TA贡献1784条经验 获得超9个赞
想
return a + sumInts(a + 1, b: b)
TA贡献1877条经验 获得超1个赞
1.函数被递归调用,直到满足条件。那个条件是 a > b
..当满足此条件时,返回0。乍一看,我希望返回值为0,这显然是不正确的。
sumInts(2,5)
I want to compute sumInts(2, 5) for this, I need to compute sumInts(3, 5) and add 2 to the result. I want to compute sumInts(3, 5) for this, I need to compute sumInts(4, 5) and add 3 to the result. I want to compute sumInts(4, 5) for this, I need to compute sumInts(5, 5) and add 4 to the result. I want to compute sumInts(5, 5) for this, I need to compute sumInts(6, 5) and add 5 to the result. I want to compute sumInts(6, 5) since 6 > 5, this is zero. The computation yielded 0, therefore I shall return 5 = 5 + 0. The computation yielded 5, therefore I shall return 9 = 4 + 5. The computation yielded 9, therefore I shall return 12 = 3 + 9. The computation yielded 12, therefore I shall return 14 = 2 + 12.
sumInts
2.在每次迭代中输出‘a’值将产生一个我所期望的值:2、3、4、5(在这里,5+1>b满足第一个条件:a>b),但我仍然不知道如何实现14的值。
a
a
TA贡献1841条经验 获得超3个赞
sumInts(a: 2, b: 5) will return: 2 + sumInts(a: 3, b: 5) sumInts(a: 3, b: 5) will return: 3 + sumInts(a: 4, b: 5) sumInts(a: 4, b: 5) will return: 4 + sumInts(a: 5, b: 5) sumInts(a: 5, b: 5) will return: 5 + sumInts(a: 6, b: 5) sumInts(a: 6, b: 5) will return: 0
sumInts(a: 6, b: 5) = 0 sumInts(a: 5, b: 5) = 5 + 0 = 5 sumInts(a: 4, b: 5) = 4 + 5 = 9 sumInts(a: 3, b: 5) = 3 + 9 = 12 sumInts(a: 2, b: 5) = 2 + 12 = 14.
sumInts(a: 2, b: 5) = 2 + sumInts(a: 3, b: 5) sumInts(a: 2, b: 5) = 2 + 3 + sumInts(a: 4, b: 5) sumInts(a: 2, b: 5) = 2 + 3 + 4 + sumInts(a: 5, b: 5) sumInts(a: 2, b: 5) = 2 + 3 + 4 + 5 + sumInts(a: 6, b: 5) sumInts(a: 2, b: 5) = 2 + 3 + 4 + 5 + 0 sumInts(a: 2, b: 5) = 14
添加回答
举报