開始使用免費開始

計算 5 的階乘

一個重要的數學運算是正整數 n 的階乘。n 的階乘定義為所有小於等於 n 的正整數相乘。例如,3 的階乘(記為 n!)定義如下:

3! = 1 x 2 x 3 = 6

要計算 n 的階乘有很多方法。在這個練習中,你會用 SQL 以迭代方式求出 5 的階乘。你可以使用 DECLARE @local_variable 在 SQL Server 中宣告變數。

回想 WHILE 迴圈的語法如下:

WHILE condition
BEGIN
   {...statements...}
END;

本練習屬於課程

SQL Server 的階層式與遞迴查詢

檢視課程

練習說明

  • 將作為終止條件的 @target 階乘目標設為 5。
  • 初始化 @factorial 結果變數。
  • 以目前的階乘結果乘上本次迭代的數值,更新 @factorial
  • 在每次迭代結束時,將終止條件減少 1。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

-- Define the target factorial number
DECLARE @target float = ___
-- Initialization of the factorial result
DECLARE @factorial float = ___

WHILE @target > 0 
BEGIN
	-- Calculate the factorial number
	SET @factorial = @___ * @___
	-- Reduce the termination condition  
	SET @target = @___ - 1
END

SELECT @factorial;
編輯並執行程式碼