简体   繁体   English

阶乘递归

[英]Factorial Recursion

I have searched the site, and though it has been answered many times, I still have one more question. 我已经搜索了该站点,尽管已经回答了很多次,但我还有一个问题。

I have the code to do the factorial with recursion. 我有代码来做递归阶乘。 I am just having trouble with the easiest part of it. 我只是在最简单的部分遇到麻烦。

When printing, my project requires that it should print: 在打印时,我的项目要求它应打印:

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

How do I get a for loop, or recursive way to get the "(4 x 3 x 2 x 1)" to work with any value of n? 如何获得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");
    }
}

And the output: 并输出:

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

A very simple solution using a for loop will be 使用for循环的一个非常简单的解决方案是

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

Your code works, you only forgot one thing: 您的代码有效,您只忘记了一件事:

Which is the variable used for counting the iterations of the for loop in the Print method? 在Print方法中,哪个变量用于计算for循环的迭代次数? What are its values inside the loop? 循环内的值是什么?

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));
    }

}

Try to get it on your own, but if you can't... 尝试自己获取,但如果不能...

...the problem is that you're printing n instead of i . ...问题是您要打印n而不是i In the loop, the variable that is decremented is i via i-- . 在循环中,通过i--递减的变量是i It starts from num and gets smaller and smaller... That's what you need to print! 它从num开始,越来越小...这就是您需要打印的内容!

Changhe the print to: 昌河印刷厂:

System.out.print(i + "x");

Your task is to get rid of the last printed x ! 您的任务是摆脱最后打印的x ;D ; D

As per the loop condition, your loop must stop when i reaches 1 to have 根据循环条件,当i达到1时,循环必须停止

(num) x (num-1) x .. x 2 x 1 (no 0!!) (num)x(num-1)x .. x 2 x 1 (no 0 !!)
So the condition will be for(int i = n; i >= 1;i--) 因此条件将为for(int i = n; i >= 1;i--)

You could incorporate printing the list of multiplied values directly into the recursion rather than adding a looping print. 您可以将打印乘法值列表直接合并到递归中,而不是添加循环打印。 Put appropriate print() statements in both the if and else clauses of your recursion. 在递归的ifelse子句中都放置适当的print()语句。 For the former, just print "1 = " . 对于前者,只需打印"1 = " For the latter, print number + " x " . 对于后者,打印number + " x "

You don't actually need the local variable result . 您实际上不需要局部变量result I'd also recommend using Java conventions regarding capitalization: method names should begin with a lower case letter, upper case indicates a class or interface. 我还建议使用有关大写的Java约定:方法名称应以小写字母开头,大写表示类或接口。 Finally, I changed the return type to long because factorials are integer-based, even though they can quickly get big. 最后,我将返回类型更改为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));
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM