阶乘递归



我已经搜索了该网站,尽管已经回答了很多次,但我还有一个问题。

我有代码可以使用递归进行阶乘运算。我只是在最简单的部分遇到麻烦。

打印

时,我的项目要求它应该打印:

4! is equal to 4 x 3 x 2 x 1 = 24

如何获得for循环或递归方式,以使"(4 x 3 x 2 x 1)"处理 n 的任何值?

import java.util.Scanner;
public class Factorial 
{
    public static void main(String args[])
    {
        System.out.println("Enter an integer:");
        Scanner keyboard= new Scanner(System.in);
        int num=keyboard.nextInt();
        System.out.print(num+ "!"+ " is equal to ");
        Print(num);
        System.out.print(FactorialCalc(num));
    }
    public static double FactorialCalc(int number)
    {
        double result;
        if(number<=1)
        {    
            result= 1;                  
            return result;
        }    
        else
        {
            return result= number * FactorialCalc(number-1);
        }
    }
    public static void Print(int n)
    {
        for(int i=n; i<=0;i--)
        {
            System.out.print(n + 'x' + (n-1));
        }
    }
}
public static void Print(int n) {
    for (int i = n; i > 0; i--) {
        System.out.print(i);
        if (i == 1) {
            System.out.print("=");
            continue;
        }
        System.out.print("x");
    }
}

和输出:

Enter an integer:
4
4! is equal to 4x3x2x1=24.0

使用 for 循环的一个非常简单的解决方案是

int fact=1;
for(int i=1;i<n;i++)
fact=fact*i;

你的代码有效,你只忘记了一件事:

哪个变量用于计算 Print 方法中 for 循环的迭代次数?它在循环中的值是什么?

public static void Print(int n)
{
    for(int i=n; i<=0;i--) //i minor or equal 0? When does the loop need to finish?
                           //What happens if you multiply something with 0?
    {
        System.out.print(n + 'x' + (n-1));
    }
}

尝试自己获取它,但如果你不能...

<块引用类>

。问题是您正在打印n而不是i。 在循环中,递减的变量通过 i-- i。它从num开始,变得越来越小...这就是您需要打印的内容!

昌河打印到:


System.out.print(i + "x");
你的任务是摆脱最后打印的x
;D
根据循环条件,当i达到 1
时,您的循环必须停止才能
(数字) x (数字-1) x ..x 2 x 1 (没有 0!!)
所以条件会for(int i = n; i >= 1;i--)

您可以将打印乘以值列表直接合并到递归中,而不是添加循环打印。 在递归的 ifelse 子句中放置适当的 print() 语句。 对于前者,只需打印"1 = ". 对于后者,请打印number + " x " .

您实际上不需要局部变量result。 我还建议使用关于大写的 Java 约定:方法名称应以小写字母开头,大写表示类或接口。 最后,我将返回类型更改为 long,因为阶乘是基于整数的,即使它们很快就会变大。

import java.util.Scanner;
public class Factorial {
   public static long printFactorial(int number) {
      if(number <= 1) {    
         System.out.print("1 = ");
         return 1;
      } else {
         System.out.print(number + " x ");
         return number * printFactorial(number-1);
      }
   }
   public static void main(String args[]) {
      System.out.print("Enter an integer: ");
      Scanner keyboard= new Scanner(System.in);
      int num=keyboard.nextInt();
      System.out.print(num + "! is equal to ");
      System.out.println(printFactorial(num));
   }
}

最新更新