开始使用免费开始使用

计算 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;
编辑并运行代码