PHP 程序:查找三个数中的最大值


2023 年 10 月 27 日, Learn eTutorial
6853

如何查找三个数中的最大值?

要查找三个数中的最大值,我们可以采用多种方法。在本 PHP 程序中,在从用户获取三个数字后,**检查第一个数字是否大于第二个和第三个数字,如果为真,则将第一个数字打印为最大值。如果此测试失败,则比较第二个和第三个数字并打印最大值。**

例如,如果输入的数字是 **5 8 9**,则输出将是 **9**。

在 PHP 中,有一个预定义函数用于检查最大值。`**max()**` 函数返回数组或元素列表中最大的值。

这是查找最大数字最简单的方法。


<?php
  $num1 = readline("Enter the 1st number: ");
  $num2 = readline("Enter the 2nd number: ");
  $num3 = readline("Enter the 3rd number: ");
  echo "Greatest among $num1 $num2 $num3 is " . max($num1, $num2, $num3);
 ?>
 

如何使用 PHP 中的用户自定义函数查找三个数中的最大值?

cfind greatest of three number

在此 PHP 程序中,我们使用用户自定义函数 **checkNum()** 来查找三个数中的最大值。

  • 首先,我们必须将三个值分别存入变量 **num1、num2、num3**,并将这些值作为用户自定义函数 **checkNum()** 的参数传入。
  • 打印函数的返回值作为三个数中的最大值。

函数内部

在函数 **checkNum()** 中,我们将获取三个参数 **n1、n2、n3**。现在我们必须检查条件 **'n1 > n2'** 和 **'n1 > n3'**,如果两者都为真,则将变量 **n1** 的值赋给变量 **greatest**。

否则,检查条件 **'n2 > n3'**,如果条件为真,则将变量 **n2** 的值赋给变量 **greatest**。

否则,将变量 **n3** 的值赋给变量 **greatest**。最后,返回变量 **greatest** 作为三个数中的最大值。

算法

**步骤 1:** 从用户获取三个值,分别存入变量 **num1、num2、num3**

**步骤 2:** 打印用户自定义函数 **checkNum()** 的返回值,其中参数为 **num1、num2、num3**,作为输入的三个数中的最大值。

函数:**checkNum(n1, n2, n3)**

**步骤 1:** 检查条件 **'n1 > n2'** 和 **'n1 > n3'**,如果两者都为真,则将变量 **n1** 的值赋给变量 **greatest**,否则转到步骤 2

**步骤 2:** 检查条件 **'n2 > n3'**,如果条件为真,则将变量 **n2** 的值赋给变量 **greatest**,否则转到步骤 3

**步骤 3:** 将变量 **n3** 的值赋给变量 **greatest**

**步骤 4:** 返回变量 **greatest** 的值作为三个数中的最大值

PHP 源代码

                                          <?php
function checkNum($n1, $n2, $n3)
{
    if ($n1 > $n2 && $n1 > $n3)
        $greatest= $n1;
    elseif ($n2 > $n3)
        $greatest= $n2;
    else
        $greatest= $n3;
    return $greatest;
}
$num1 = readline("Enter the 1st number: ");
$num2 = readline("Enter the 2nd number: ");
$num3 = readline("Enter the 3rd number: ");
echo "Greatest among $num1 $num2 $num3 is " . checkNum($num1, $num2, $num3);
?>
                                      

输出

Enter the 1st number: 7
Enter the 2nd number: 45
Enter the 3rd number: 20
Greatest among 7 45 20 is 45