编写一个 C++ 程序,通过示例查找闰年。在此闰年示例中,我们使用 If 语句来检查
- year % 400 等于 0 – 可被 400 整除的年份是闰年。
- ( year % 4 == 0 ) && ( year % 100 != 0)) – 任何可被 4 整除但又不是世纪年份的年份,则是闰年。
#include<iostream>
using namespace std;
int main()
{
int year;
cout << "\nPlease Enter the Year to Check the Leap Year = ";
cin >> year;
if (( year % 400 == 0) || (( year % 4 == 0 ) && ( year % 100 != 0)))
{
cout << "\n" << year << " is a Leap Year";
}
else
{
cout << "\n" << year << " is Not a Leap Year";
}
return 0;
}

让我再检查一下。
Please Enter the Year to Check the Leap Year = 2020
2020 is a Leap Year
下面的程序接受一个整数,并使用 Else If 语句查找它是闰年还是非闰年。
#include<iostream>
using namespace std;
int main()
{
int year;
cout << "\nPlease Enter the Year to Check = ";
cin >> year;
if (year % 400 == 0)
{
cout << "\n" << year << " is a Leap Year";
}
else if ( year%100 == 0)
{
cout << "\n" << year << " is Not a Leap Year";
}
else if ( year % 4 == 0 )
{
cout << "\n" << year << " is a Leap Year";
}
else
{
cout << "\n" << year << " is Not a Leap Year";
}
return 0;
}
Please Enter the Year to Check = 2024
2024 is a Leap Year
此 程序 有助于使用嵌套 If 语句检查年份是否为闰年。
#include<iostream>
using namespace std;
int main()
{
int year;
cout << "\nPlease Enter the Year to Check = ";
cin >> year;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
{
cout << "\n" << year << " is a Leap Year";
}
else
{
cout << "\n" << year << " is Not a Leap Year";
}
}
else
{
cout << "\n" << year << " is a Leap Year";
}
}
else
{
cout << "\n" << year << " is Not a Leap Year";
}
return 0;
}
Please Enter the Year to Check = 2016
2016 is a Leap Year