在PHP中找到数字的阶乘
给定一个数字,我们必须找到它的阶乘。
查找阶乘的公式:5!(5的方格)=5x4x3x2x1=120
示例
Input: 5 Output: 120
在PHP中查找数字阶乘的程序
<?php //查找数字阶乘的程序 //在这里,我们正在设计一个功能 //将数字作为参数并返回 //该数字的阶乘 //功能:getFactorial- function getFactorial($num){ //声明一个变量并赋值为1- $factorial = 1; for($loop = 1; $loop <= $num; $loop++) $factorial = $factorial * $loop; return $factorial; } //测试上述功能的主代码 $number = 1; print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n"); $number = 2; print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n"); $number = 3; print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n"); $number = 4; print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n"); $number = 5; print_r("Factorial of ".$number. " is = ".getFactorial($number). "\n"); ?>
输出结果
Factorial of 1 is = 1 Factorial of 2 is = 2 Factorial of 3 is = 6 Factorial of 4 is = 24 Factorial of 5 is = 120