PHP 程序:检查年份是否为闰年


2022年4月17日, Learn eTutorial
2809

什么是闰年?

闰年是包含 **366** 天的年份。实际上,我们理解它是要检查二月是否有 28 天。例如,**2004** 是一个**闰年**,而 **2005** 是一个**平年**。

如何使用 PHP 检查年份是否为闰年?

在此程序中,我们使用用户定义函数来检查用户输入的年份是否为闰年。要检查年份是否为闰年,我们将检查输入的年份是否能被 **4** 整除但不能被 **100** 整除,如果这些条件为真,则为闰年。然后我们将检查年份是否不能被 **400** 整除,如果为真,则不是闰年,在所有其他情况下,它将是闰年。

算法

**步骤 1:** 从用户读取年份并将其赋值给变量 **year**

**步骤 2:** 将用户定义函数 **isLeap()** 的返回值(以变量 year 的值作为参数)赋值给变量 **check**

**步骤 3:** 检查条件:如果变量 **check** 的值为 **1**,则打印输入的年份是闰年,否则打印输入的年份不是闰年

算法用户定义函数:isLeap(year)

**步骤 1:** 检查条件 **'year % 4 == 0'** 和 **'year % 100 != 0'** 是否为真,如果是则返回值为 **1**

**步骤 2:** 检查条件 **'year % 400 != 0'**,如果条件为真,则返回值为 **0**

**步骤 3:** 如果以上两个步骤都为假,则返回值为 **1**

PHP 源代码

                                          <?php
function isLeap($year)
{
    if ($year % 4 == 0 && $year % 100 != 0) {
        return 1;
    } else if ($year % 400 != 0) {
        return 0;
    } else {
        return 1;
    }
}
$year = readline("Enter the year: ");
$check = isLeap($year);
if ($check == 1) {
    echo "$year is a leap year";
} else {
    echo "$year is not a leap year";
}
?>
                                      

输出

Example 1
Enter the year: 2012
2012 is a leap year

Example 2
Enter the year: 2014
2014 is not a leap year