我无法弄清楚代码中缺少什么。任何帮助将不胜感激。我是编码新手,我只是在做一些练习。谢谢!
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 :(得分:2)
您缺少特殊情况(为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);
}
答案 1 :(得分:2)
在递归模式下:`
import java.util.Scanner;
import java.lang.Math;
class Factorial {
public static Scanner sc;
public static int factorial(int n) {
if(n==0)return 1;
return n*factorial(n-1);
}
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(factorial(myNumber));
}
}`
答案 2 :(得分:1)
好吧...。无论您在n上提供什么,您总会返回factorial(0)
,最终会导致对factorial
的无休止的调用循环,所以我想您的堆栈将被重击并获得堆栈溢出错误,对不对?我认为这就是错误所在。
答案 3 :(得分:1)
对于每个递归函数,您都必须编写一个基本案例,否则它将最终进行递归,最后将导致堆栈溢出错误(不是该站点的名称,这是一个错误),这就是您的算法就在那里丢失了。
用于递归查找阶乘
n! = n x(n-1)!,并且基本情况为 0! = 1
// somewhere in your class
int factorial(int n) {
// base case
if (n == 0) return 1;
// recursion
return n * factorial(n-1);
}
答案 4 :(得分:1)
将此代码替换为您的代码:
int factorial=1;
int factorial(int n) {
for (int j = 1; j <= n; j++) {
factorial = factorial * j;
}
return factorial;
}