我可以通过使用 for 循环来做到这一点,但它太长了。我必须执行大约 10 个 for 循环。
System.out.println("factorial of 10");
int fact = 1;
for (int x=1;x<=10;x++) {
fact=fact*x;
System.out.println(fact);
}
System.out.println(" factorial of 20 ");
double fact1 = 1;
for (double y=1;y<=20;y++){
fact1=fact1*y;
System.out.println(fact1);
}
最佳答案
您可以使用递归方法来计算阶乘。还可以根据您在解决方案中调整类型。例如 BigInteger
或 Long
public class Factorial {
public static void main (String[] args) {
int theNum, theFact;
System.out.println("This program computes the factorial " +
"of a number.");
System.out.print("Enter a number: ");
theNum=Console.in.readInt();
theFact = fact(theNum);
System.out.println(theNum + "! = " + theFact + ".");
}
static int fact(int n) {
if (n <= 1) {
return 1;
}
else {
return n * fact(n-1);
}
}
}
关于java - 计算 10 .. 100 的阶乘而不重复任何代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773164/