使用递归向上和向下计数 [英] Counting numbers up and down using Recursion
问题描述
给出两个数字,比如说 start = 1
和 end = 4
,我试图按顺序依次计算所有数字.不允许循环
Given two numbers, let's say start = 1
and end = 4
, I am trying to count all the numbers in sequence up and then down . No looping is allowed
1 2 3 4 3 2 1
我尝试编写递归函数.该函数正在向上计数并打印1 2 3 4,但是当我尝试向下计数时,我期望 4 3 2 1
但我陷入无限循环.原因是起始值在递归中丢失,并且我不知道从下往上数时在哪里停止.
I tried writing a recursion function. The function is counting up fine and its printing 1 2 3 4 but when I try to count down, I expect 4 3 2 1
but I get into an infinite loop. The reason is the start value is lost in recursion and I don't know where to stop when counting from bottom up.
我已经花了4个小时了.我们甚至可以递归进行此操作吗?递归是一种方式
I have spent 4 hours on this . Can we even do this in recursion ? Is recursion one way
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);
}
}
推荐答案
您只需要使用递归进行计数即可.然后,当函数返回时,您就走下了路.这可以通过以下方式实现:
You just have to use the recursion for counting up. Then, when the function returns, you are on your way down. This can be achieved with:
public void countUpAndDown(int start, int end) {
System.out.println(start);
if (end == start) return;
countUpAndDown(start+1, end);
System.out.println(start);
}
这篇关于使用递归向上和向下计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!