【发布时间】:2016-09-14 06:18:01
【问题描述】:
给定两个数字,比方说start = 1 和end = 4,我试图按顺序计算所有数字 up 然后 down 。不允许循环
1 2 3 4 3 2 1
我尝试编写递归函数。该函数计数正常,打印 1 2 3 4 但是当我尝试倒数时,我希望 4 3 2 1 但我进入了无限循环。原因是递归中丢失了起始值,从下向上计数时我不知道在哪里停止。
我在这上面花了 4 个小时。我们甚至可以在递归中做到这一点吗?递归是一种方式吗
public static void countUpDown(int start, int end) {
//to pring bottom up -> 4 3 2 1
if ( start > end && end > 0) {
System.out.println(end - 1);
countUpDown(start, end - 1);
}
//to print up 1 2 3 4
if (start <= end) {
System.out.println("-->" + start);
countUpDown(start + 1, end);
}
}
【问题讨论】:
-
任何帮助我走向正确的方向都会有所帮助