gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:33:28 24 4
gpt4 key购买 nike

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);
}
}
}

我想打印出这样的东西:

0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)

我得到的是:

0 (30!)
1 (30!)
...etc, up to 30

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

最佳答案

这很简单。您无需定义变量,而是每次都使用更新后的 x 调用方法:

System.out.println(x + " " + factorial(x));

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

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

注意一些事情:

  1. x++。它基本上是 x = x + 1 的缩写形式,但有一些注意事项。参见 this question了解更多相关信息。
  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);
}
}

因为BigInteger#toString()的魔力,您无需更改 main 中的任何内容即可使其工作,但我仍然建议遵循上述建议。

关于java - 如何在表格上打印 0-30 的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com