java 递归数字打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4078630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recursive Number Printing
提问by Catie
If the number 5 is given to us, it needs to be printed out on the console like 1, 2, 3, 4, 5. This needs to be done recursively. (Java preferably)
如果给我们数字 5,它需要像 1、2、3、4、5 一样在控制台上打印出来。这需要递归完成。(最好是Java)
In case anyone is wondering these are not homework questions. I am practicing for my midterm a week from now.
如果有人想知道这些不是家庭作业问题。一周后我正在练习我的期中考试。
Sorry about not posting my work. I was doing something like the below: but getting confused with where to print the rest of the number, and how to stop recursively calling the method with (n - 1). Jacob with his post helped me out. Thanks to everyone who helped.
很抱歉没有发布我的作品。我正在做类似下面的事情:但是对在哪里打印剩余数字以及如何停止递归调用(n - 1)的方法感到困惑。雅各布和他的职位帮助了我。感谢所有帮助过的人。
public void writeNums(int n) {
if (n < 1)
throw new IllegalArgumentException();
if (n == 1) {
System.out.print("1, ");
}
writeNums(n - 1);
回答by Jacob Mattison
We're not going to write your code for you, but the way recursion works is that you have a function that calls itself, passing in some parameter that changes for each call. It needs to handle the "base case" in which the function does something but doesn't need to call itself anymore, and also handle the "general case" where the function both does something and calls itself to complete whatever needs to be done. So:
我们不会为您编写代码,但递归的工作方式是您有一个调用自身的函数,传入一些随每次调用而更改的参数。它需要处理函数做某事但不再需要调用自身的“基本情况”,还需要处理函数既做某事又调用自身以完成需要完成的任何事情的“一般情况”。所以:
function printNumbersUpTo( current )
if current is 1, print 1 and return. //base case
otherwise, call printNumbersUpTo( current - 1), then print current, and return. //general case
回答by Itay Karo
Lets start by writing a function that doesn't do much but it is some obvious skeleton for basic recursive function
让我们从编写一个功能不多的函数开始,但它是基本递归函数的一些明显骨架
void Print(int num)
{
if (num <= 0)
return;
Print(num - 1);
}
Now try to think where to add the atual print to console in order for the number to appear in the correct order.
现在尝试考虑在何处将 atual 打印添加到控制台,以便数字以正确的顺序出现。
回答by Michael McGowan
If you struggled with this problem, you probably want to review how recursion in general works: http://en.wikipedia.org/wiki/Recursion_%28computer_science%29
如果你在这个问题上挣扎,你可能想回顾一下递归的一般工作原理:http: //en.wikipedia.org/wiki/Recursion_%28computer_science%29
Think about how the base case should be handled, and think about how the general case should be handled. When done right it often it can feel remarkably simple.
考虑基本情况应该如何处理,考虑一般情况应该如何处理。如果做得对,它通常会感觉非常简单。
回答by girman
private static String Print(int num) {
if (num <= 1) // base case
return Integer.toString(num);
else
return Print(num - 1) + ", " + num;
}
}