【问题标题】:How do i write a program that finds the factorial of numbers 1-15我如何编写一个找到数字 1-15 的阶乘的程序
【发布时间】:2014-12-22 23:16:17
【问题描述】:

我有一个作业,但我不明白如何编写一个计算阶乘的程序。 我已经想出了如何通过用户输入来做到这一点,但我是初学者,我不知道如何从 1 到 15 做到这一点。 我目前有这个,但我不知道如何将其应用于非用户输入程序

while (true) {
    int factorial,fact=1;
    System.out.println("Enter a number to execute a factorial function");
    factorial = Integer.parseInt(br.readLine());
    if (factorial <=0){
        System.out.println("Factorial is undefined");
    }
    else {
        for(int i =1;i<=factorial;i++){

            fact = fact * i;
        }
    }
    System.out.println("The factorial of your number is " + fact);

【问题讨论】:

  • 在这里提问之前尝试一些东西总是有帮助的。
  • 计算阶乘是一项非常常见的编程任务。如果您搜索,您应该无法找到各种示例。你的书中可能有一个。
  • 又是一个阶乘问题?我开始觉得老了!
  • 提示:使用递归。尝试先编写伪代码,然后再编写实际的 java 代码。这就是你将如何学习

标签: java


【解决方案1】:
public static int fact(int num){
    if(num <= 1){
        return 1;
    }
    return num * fact(num-1);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
相关资源
最近更新 更多