我正在尝试以两种不同的方式进行阶乘方法。第一个是迭代方法,非常适合打印。我在打印递归方法时遇到困难,该方法是 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
}
最佳答案
How would I go about printing out the recursive method by using input the same as the iterative way?
用同样的方法你做不到。以递归方式,输入数字的提示会反复出现。您需要在 main 方法中单独创建以下三行。
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
iFactorial(fact);
//Call the recursive method
rFactorial(fact);
}
关于java - 使用用户输入打印出 int 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19166753/