Java 阶乘程序

标签 java algorithm for-loop recursion math

我无法弄清楚我的代码中缺少什么。任何帮助将不胜感激。我是编码新手,我只是在做一些练习。谢谢!

import java.util.Scanner;
import java.lang.Math;

public class Factorial {

    public static Scanner sc;

    public Factorial() {
    }

    int factorial(int n) {
        for (int j = n - 1; j > 0; j--) {
            int factorial = factorial(0) * j;
        }
        return factorial(0);
    }

    public static void main(String[] args) {

        System.out.print("Enter a number to find its factorial: ");
        sc = new Scanner(System.in);
        int myNumber = sc.nextInt();

        Factorial myFactorial = new Factorial();
        System.out.println(myFactorial.factorial(myNumber));
    }
}

最佳答案

你错过了角落案例(0):

int factorial(int n) {
    if (n == 0) return 1;
    for (int j = n - 1; j > 0; j--) {
        int factorial = factorial(0) * j;
    }
    return factorial(0);
}

关于Java 阶乘程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848845/

相关文章:

java - 如何在 Codename One 中应用多种布局?

java - 为不同数据库生成脚本的最佳选择

c++ - 使用 C++ 的数组中出现次数最多的元素?

c - For循环两个数字之间的数字和

python - 编写相同的 n 层嵌套循环

java - 使用 ibatis 将 HashMap 值插入到表中

java - 作为字符的数字是否比作为整数的数字占用更少的空间?

python graph_tool : get _all_ shortest paths

arrays - 使用多个索引 :[Int] 枚举多线性映射的 Swift 算法

windows - 根据搜索字符串从 REG QUERY 中提取特定注册表项