PHP 程序:检查数字是正数、负数还是零


2022年5月11日, Learn eTutorial
4265

这是一个简单的 PHP 数字基础程序。我们将从用户那里读取一个数字,并使用 PHP 中的条件语句检查它是正数、负数还是零。为了更好地理解该程序,我们建议您阅读以下 PHP 主题。

如何判断一个数字是正数、负数还是零?

在此程序中,我们需要检查输入的值是正数、负数还是零。为此,我们首先读取数字,然后检查该数字是大于零还是小于零。

  • 如果数字大于 0,则给定数字为正数。
  • 如果数字小于 0,则给定数字为负数。
  • 如果数字等于 0,则用户输入为零。

如何使用 PHP 检查数字是正数、负数还是零?

在此程序中,我们接受用户输入的数字并将其赋值给变量 num。然后我们检查 is_numeric(num) 是真还是假,这里我们使用内置函数 is_numeric() 来检查变量 num 的值是否为数字。如果不是数字,则打印“输入一个有效数字”,否则我们必须检查条件 num > 0,如果为真则打印 num 为正数,否则检查条件 num < 0,如果为真则打印 num 为负数,否则打印 num 为零。

算法

步骤 1: 从用户那里获取数字并将其赋值给变量 num

步骤 2: 然后我们检查条件 '!is_numeric(num)'(这里我们使用内置函数 is_numeric() 来检查变量的值是否为数字,并使用 '!'(非)来反转它,以检查输入的值是否不是数字)如果为真,则打印“输入一个有效数字”,否则进入下一步

步骤 3: 检查条件 'num > 0',如果为真,则打印变量的值为正数,否则进入下一步

步骤 4: 检查条件 'num < 0',如果为真,则打印变量的值为负数,否则打印变量的值为零

PHP 源代码

                                          <?php
$num = readline("Enter the number to be checked: \n");
if (!is_numeric($num))
    echo "Enter a valid number";
elseif ($num > 0)
    echo "The entered number $num is positive";
elseif ($num < 0)
    echo "The entered number $num is negative";
else {
    echo "The entered number $num is zero";
}
?
                                      

输出

Example 1
Enter the number to be checked:  57
The entered number 57 is positive

Example 2
Enter the number to be checked:  -14
The entered number -14 is negative

Example 3
Enter the number to be checked:  0
The entered number 0 is zero

Example 4
Enter the number to be checked:  a
Enter a valid number