可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I can't figure out what I'm missing on my code. Any help will be greatly appreciated. I'm new in coding and I'm just doing some practice. Thank you!
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));
}
}
回答1:
You're missing the corner case (for 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);
}
回答2:
In recursive mode : `
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));
}
}`
回答3:
For every recursive function, you must need to write a base case else it will end up doing recursion and at the end it will cause stack overflow error(not the name of this site, it is an error), which is what you are missing right there in your algorithm.
For finding factorial recursively
Mathematically
n! = n x (n - 1)! and the base case is 0! = 1
In Java
// somewhere in your class
int factorial(int n) {
// base case
if (n == 0) return 1;
// recursion
return n * factorial(n-1);
}
回答4:
Well.... regardless of what you provide on n, you always return factorial(0) which ends up creating an endless loop of calls to factorial so I guess your stack is getting hammered and getting an Stack Overflow error, right? I think that's where the error is.
回答5:
Replace this code in your code:
int factorial=1;
int factorial(int n) {
for (int j = 1; j <= n; j++) {
factorial = factorial * j;
}
return factorial;
}