使用 while 迴圈計算給定數字的階乘的 Java 程式
數字的階乘是數學中的一個基本概念,表示從 1 到該數字的所有正整數的乘積。計算給定數字的階乘是程式設計中一個常見的問題,而 Java 提供了一種使用 while 迴圈 來實現此目的的簡單方法。某個數字 (n) 的階乘是從 0 到 n(包括 n)的所有數字的乘積,例如數字 5 的階乘為 1*2*3*4*5 = 120。
問題陳述
給定一個數字,編寫一個 Java 程式使用 while 迴圈計算其階乘。
輸入
Enter the number to which you need to find the factorial: 5
輸出
Factorial of the given number is: 120
計算給定數字階乘的步驟
以下是使用 while 迴圈計算給定數字階乘的步驟
- 步驟 1:查詢給定數字的階乘。
- 步驟 2:建立一個名為 factorial 的變數,並將其初始化為 1。
- 步驟 3:使用條件 i(初始值為 1)小於給定數字啟動 while 迴圈。
- 步驟 4:在迴圈中,將 factorial 與 i 相乘,並將結果賦值給 factorial,然後遞增 i。
- 步驟 5:最後,列印 factorial 的值。
計算數字階乘的 Java 程式
以下是使用 while 迴圈計算給定數字階乘的 Java 程式示例
import java.util.Scanner;
public class FactorialWithWhileLoop {
public static void main(String args[]){
int i =1, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
while(i <=number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is: "+factorial);
}
}
輸出
Enter the number to which you need to find the factorial: 5 Factorial of the given number is: 120
程式碼解釋
程式碼首先從 java.util 包 中匯入 Scanner 類 以讀取使用者輸入。main 方法提示使用者輸入一個數字,該數字儲存在 number 變數中。factorial 變數初始化為 1,i 變數設定為 1。while 迴圈只要 i 小於或等於 number 就持續執行。在迴圈內部,factorial 乘以 i,並且 i 遞增 1。最後,程式列印計算出的階乘值。該程式碼使用 while 迴圈迭代地將從 1 到給定數字的數字相乘,從而有效地計算階乘。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP