java - 使用用户输入打印出 int 方法

标签 java recursion

我正在尝试以两种不同的方式进行阶乘方法。第一个是迭代方法,非常适合打印。我在打印递归方法时遇到困难,该方法是 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/

相关文章:

java - 计算二叉树中所有节点的节点深度

java - Android - AsyncTask 中的 doInBackground() 错误

javascript - 直接引用node_modules可以吗?

Java if 与 try/catch 开销

Java获取对象的arrayList的类名并类型转换数组列表而不循环

c# - 尾递归的好处

java - 使用 java.util.zip 构建有效的 epub

c# - 递归搜索类别及其子类别

parsing - 为什么右递归语法不适合自下而上的 LR(k) 解析?

c - C 编程中的递归