我尝试使用 Java 中的递归来构建以下字符串。预期的输出是:
4! = 4!
= 4 * 3!
= 4 * 3 * 2!
= 4 * 3 * 2 * 1!
= 4 * 3 * 2 * 1 * 0!
这是我的阶乘方法:
public static String factorial(int n, int count, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n - count);
return factorial(n - 1, count, equation);
}
}
我在main
方法中输入以下输入:
System.out.print(factorial(4, 0, ""));
它目前打印出String" 43210!"我还没有和递归一起工作过。我做错了什么?
答案 0 :(得分:0)
我更改了一些代码,然后代码可以实现一个目标。代码也是如此。我希望这可以帮到你。
public class Snippet {
public static String factorial(int n, String equation)
{
if (n == 0) {
return equation += (n + "!");
} else {
equation += (n + "*");
return factorial(n - 1, equation);
}
}
public static void factorial1(int n, String equation)
{
if(n < 0)
{
return;
}
System.out.println(equation + n + "!");
factorial1(n - 1, equation + n + "*");
}
public static void main(String [] arg)
{
System.out.println("4! ");
System.out.println(factorial(4, "="));
System.out.println();
factorial1(4, "=");
}
}
答案 1 :(得分:0)
如果只想使用一个递归函数来实现目标,则需要嵌套递归。您可能想尝试以下内容:
public class Factorial {
public static void main(String[] args) {
System.out.println(factorial(4));
}
private static String factorial(int origNum, int lineNum, int innerLoopNum, String equation) {
if(innerLoopNum == origNum - lineNum) {
equation = equation + innerLoopNum + "!" + "\n";
}
else if(lineNum > origNum)
return equation;
else {
equation = equation + innerLoopNum + "*";
equation = factorial(origNum, lineNum, --innerLoopNum, equation);
return equation;
}
++lineNum;
if(lineNum > origNum)
return equation;
return factorial(origNum, lineNum, origNum, equation);
}
public static String factorial(int n) {
return factorial(n, 0, n, "");
}
}
答案 2 :(得分:0)
假设 n 永远不会是负数,这应该就足够了......
public String factorialString(int n) {
if (n == 0) return "0!";
return n + " * " + factorialString(n - 1);
}
只是为了好玩,你也可以把它写成:
public String factorialString(int n) {
return (n == 0)
? "0!"
: n + " * " + factorialString(n - 1);
}
对于有关人员,我知道我正在进行字符串连接,我应该使用StringBuilder。任务是在这里演示递归。