【问题标题】:Java Factorial ProgramJava 阶乘程序
【发布时间】:2019-02-24 04:49:49
【问题描述】:
我无法弄清楚我的代码中缺少什么。任何帮助将不胜感激。我是编码新手,我只是在做一些练习。谢谢!
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));
}
}
【问题讨论】:
标签:
java
algorithm
for-loop
recursion
math
【解决方案1】:
你错过了角落案例(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】:
在递归模式下:`
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】:
对于每个递归函数,你必须编写一个基本情况,否则它将最终进行递归并最终导致堆栈溢出错误(不是这个站点的名称,这是一个错误),这是什么你在你的算法中失踪了。
用于递归查找阶乘
数学
n! = n x (n - 1)!,基本情况是 0! = 1
在 Java 中
// somewhere in your class
int factorial(int n) {
// base case
if (n == 0) return 1;
// recursion
return n * factorial(n-1);
}
【解决方案4】:
嗯....不管你在 n 上提供什么,你总是返回factorial(0),这最终会创建一个对factorial 的无限循环调用,所以我猜你的堆栈正在被敲打并出现堆栈溢出错误,正确的?我认为这就是错误所在。
【解决方案5】:
在您的代码中替换此代码:
int factorial=1;
int factorial(int n) {
for (int j = 1; j <= n; j++) {
factorial = factorial * j;
}
return factorial;
}