我正在尝试以两种不同的方式进行阶乘方法。第一个是一种迭代方法,非常适合打印出来。我很难打印出递归方法,它是一种 int 方法而不是 void。我将如何使用与迭代方式相同的输入来打印递归方法?任何帮助深表感谢。我试图在我的 main 中调用每个方法。
Java代码:
import java.util.Scanner;
public class Factorial
{
public static void main(String[] args)
{
System.out.println("Enter a number");
Scanner input = new Scanner(System.in);
int fact = input.nextInt();
//Call the iterative method
int ifact = iFactorial(fact);
System.out.println("The factorial iteratively is: " + ifact);
//Call the recursive method
int rfact = rFactorial(fact);
System.out.println("The factorial recursively is: " + rfact);
}
//Iterative method starts
public static int iFactorial(int fact)
{
for(int i = fact-1; i > 0; i--)
{
fact *= i;
}
return fact;
}
//Iterative method ends
//Recursive method starts
public static int rFactorial(int fact)
{
if(fact == 1)
{
return 1;
}
else
{
return fact * rFactorial(fact-1);
}
}
//Recursive method ends
}