[英]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.