java - 计算 10 .. 100 的阶乘而不重复任何代码?

标签 java

我可以通过使用 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);
 }

最佳答案

您可以使用递归方法来计算阶乘。还可以根据您在解决方案中调整类型。例如 BigIntegerLong

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/

相关文章:

java - 从同一 Jaxb 架构文件创建多个 @XmlRootElement

java - 从 redshift 异步批量卸载

java - 在 JPA 2 中实现基于枚举的字典

java - ProcessBuilder启动java程序: IOException.无法启动进程。原因:无法运行程序CreateProcess error=2

java - 如何查找两个表之间的关系?

java - JDBC 连接池设置在 Glassfish5 上不起作用

java - Netty 4在处理程序中多次读/写

java - Json 响应值未设置为 Bean 类

java - LibGDX 光传感器数据

java - 在localhost启动tomcat v9.0服务器遇到问题