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

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 - Java析因程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54848845/

10-12 04:58