[英]Factorial Recursion
我已经搜索了该站点,尽管已经回答了很多次,但我还有一个问题。
我有代码来做递归阶乘。 我只是在最简单的部分遇到麻烦。
在打印时,我的项目要求它应打印:
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时,循环必须停止
(num)x(num-1)x .. x 2 x 1 (no 0 !!)
因此条件将为for(int i = n; i >= 1;i--)
您可以将打印乘法值列表直接合并到递归中,而不是添加循环打印。 在递归的if
和else
子句中都放置适当的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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.