我们将编写三个 java 程序来查找数字的阶乘。 1)使用for
循环 2)使用while
循环 3)找到用户输入的数字的阶乘。在完成程序之前,让我们理解什么是阶乘:数字n
的因子表示为n!
,n!
的值表示为:1 * 2 * 3 * ... * (n-1) * n
我们在程序中使用循环实现了相同的逻辑。
示例:使用for
循环查找阶乘
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
输出:
Factorial of 5 is: 120
示例 2:使用while
循环查找阶乘
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number = 5;
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
输出:
Factorial of 5 is: 120
示例 3:查找用户输入的数字的阶乘
程序使用while
循环查找输入数的阶乘。
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
输出:
Enter the number:
6
Factorial of 6 is: 720