一个数的阶乘是指从 1 到给定数字的所有整数的乘积。正整数的阶乘用 n! 表示(其中 n 是该数字)。例如,数字 3 的阶乘(表示为 3!)是 3 * 2 * 1,即 6。在这个程序中,我们使用 for 循环 来查找一个数的阶乘。0 的阶乘始终是 1。
为了在 PHP 中查找一个数的阶乘,我们使用 for 循环。首先,我们从用户那里获取整数并将其保存到一个变量中。然后我们应该检查该数字是正数还是负数。如果该数字是负数,我们应该显示错误消息,否则继续。现在我们可以执行 for 循环,直到满足条件并获得结果。
步骤 1:使用 PHP 函数 readline 将整数读取到变量 num 中。
步骤 2:将值 1 赋给变量 fact 以存储阶乘结果。
步骤 4:使用 if 语句检查 num 的值是否为正数。如果为正数,则执行以下步骤,否则使用 echo 打印“输入一个正数”。
步骤 5:执行 for 循环,并将变量 fact 的值赋给变量 x,然后执行子步骤,直到条件“fact >= 0”变为假,并在每次迭代中递减变量 x 的值
(i) 'fact *= x'
步骤 6:使用 echo 打印变量 fact 的值作为输入的数字的阶乘。
<?php
$num = (int)readline("Enter the number: "); // read number from user and type casted into integer
$fact = 1;
if ($num >= 0) { // checking the number is positive or negative
for ($x = $num; $x >= 1; $x--) {
$fact *= $x; // multplying the value of fact with x
}
echo "Factorial of $num is $fact";
} else {
echo "Enter a positive integer.";
}
?>
Enter the number: 4 Factorial of 4 is 24