原文: https://beginnersbook.com/2017/09/java-program-to-find-factorial-using-for-and-while-loop/
我们将编写三个 java 程序来查找数字的阶乘。 1)使用for循环 2)使用while循环 3)找到用户输入的数字的阶乘。在完成程序之前,让我们理解什么是阶乘:数字n的因子表示为n!,n!的值表示为:1 * 2 * 3 * ... * (n-1) * n
我们在程序中使用循环实现了相同的逻辑。要了解这些程序,您应该具备以下 java 教程主题的基本知识:
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: 120public 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程序使用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