使用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:啟動while迴圈,條件為i(初始值為1)小於給定數字。
- 步驟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到給定數字的數字相乘,從而有效地計算階乘。
廣告