问题
I am trying to use a recursive program to print out a sequence that starts at one value, goes to a max, then back down to the original value. The program can't use static or global variables, or use an array.
Ex: f(5,10)
prints 5,6,7,8,9,10,9,8,7,6,5
I think I have the concept down, at least I think I do, but I can't figure out how to print the variable from the recursive method to print the sequence.
Here is my program:
public class recursive {
public static int f(int a, int b) {
System.out.print(a);
if (a == b) return a;
else return a + f(a + 1, b) + a;
public static void main(String[] args) {
f(2, 5);
}
}
Do I need to Change the program to be able to print? I am fairly certain my concept is correct, I just can't print it. Please help!!!!
回答1:
If you must print inside the recursive function, just print instead of returning..
public static void f(int a, int b) {
if (a == b) {
System.out.print(a);
}
else {
System.out.print(a + ",");
f(a+1,b);
System.out.print("," + a);
}
}
回答2:
You can think of your output as a nested series of outputs. For instance, with f(5, 10)
, you should print a 5, then a comma, print f(6, 10)
, then print a comma and another 5. You just need to then identify and deal with the base case (where you don't recurse) and you will be done.
回答3:
If you can't use an array, that main(String []args) is going to be a problem ;)
What you want to do is:
boilerplate boilerplate void recursive(num, max) {
System.out.print(num)
if (number < max) {
System.out.print(",");
recursive(+1, max);
}
System.out.print(num)
}
boilerplate boilerplate main(String[] args) {
recursive(1, 10);
}
Disclaimer: it's been about 15 years since I did java, so there's probably something very wrong with this -- apart from the "boilerplate" stuff ;)
回答4:
public class recursive {
public static void f(int a, int b) {
if (a == b) {
System.out.print(a);
} else {
System.out.print(a + ",");
f(a + 1, b);
System.out.print("," + a);
}
}
public static void main(String[] args) {
f(2, 5);
}
}
回答5:
public static void f(int a, int b) {
if(a != b) {
System.out.print(a + ",");
if(a < b) {
f(a + 1, b);
} else {
f(a - 1, b);
}
System.out.print("," + a);
} else {
System.out.print(a);
}
}
public static void main(String[] args) {
f(2, 5); //2,3,4,5,4,3,2
System.out.println();
f(5, 2); //5,4,3,2,3,4,5
}
There were a few problems with your code:
- If a is greater than b, the code would continue to execute until you get a StackOverflowError.
- When a and b are not equal, you're returning an integer, rather than a string.
- Printing a + f(a + 1, b) + a will cause the wrong output to be printed because you're calling a print function inside of a print function.
来源:https://stackoverflow.com/questions/19236980/how-do-i-print-the-values-in-a-recursive-program-in-java