如何在表格上打印0-30的阶乘

pan*_*nzo 4 java recursion

public static void main(String[] args) {

    int n = factorial(30);
    int x = 0;
    while (x <= 30) {
        System.out.println(x + " " + n);
        x = x + 1;
    }


    public static int factorial (int n) {   
       if (n == 0) {
             return 1;
        } else {
            return n * factorial (n-1);
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

我正在尝试打印出这样的东西:

0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)
Run Code Online (Sandbox Code Playgroud)

我得到的是这样的:

0 (30!)
1 (30!)
...etc, up to 30
Run Code Online (Sandbox Code Playgroud)

换句话说,我能够创建从0到30的左列,但我想让它在右栏中打印数字的阶乘.使用我的代码,它只在右侧列中打印30的阶乘.我希望它按照相应的数字旁边的顺序打印阶乘.如何修复我的代码来执行此操作?

Fun*_*uit 9

这很简单.不是定义变量,而是x每次都使用更新的方法调用方法:

System.out.println(x + " " + factorial(x));
Run Code Online (Sandbox Code Playgroud)

请注意,您的循环可以重写为for循环,这正是它们的设计目的:

for (int x = 0; x < 30; x++) {
    System.out.println(x + " " + factorial(x));
}
Run Code Online (Sandbox Code Playgroud)

请注意以下几点:

  1. x++.它基本上是一种简短的形式x = x + 1,尽管有一些警告.有关详细信息,请参阅此问题.
  2. x循环(for (int x = ...)中定义,而不是在它之前
  3. n永远不会被定义或使用.我没有设置仅使用过一次的变量,而是直接使用了结果factorial(x).

注意:我实际上很确定int在面对30时会溢出!.265252859812191058636308480000000是一个相当大的数字.long事实证明,它也会溢出.如果要正确处理它,请使用BigInteger:

public BigInteger factorial(int n) {
    if (n == 0) {
        return BigInteger.ONE;
    } else {
        return new BigInteger(n) * factorial(n - 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于BigInteger#toString()神奇,你不需要改变任何东西main来使这项工作,虽然我仍然建议遵循上面的建议.