<>判断一年是否为闰年
两种方法:
下面这种用多个if语句嵌套判断
#include<iostream> using namespace std; int main() { int year; bool leap; cout
<< "请输入年份:" << endl; cin >> year ; if (year % 4 == 0)//年份能被4整除 { if (year % 100
== 0)//年份能被4整除同时又能被100整除 { if (year % 400 == 0)//年份能被4整除,能被100整除,还能被400整除,一定为闰年
{ leap = true; } else leap = false; } else leap = true;//年份能被4整除但不能被100整除,一定为闰年
} else leap = false;//年份不能被4整除为非闰年 if (leap) cout << year << ' ' << "is a leap
year!" << endl; else cout << year << ' ' << "is not a leap year!" << endl;
return 0; }
另一种方法,用逻辑表运算符&&和 || ,一行语句就可以实现
#include<iostream> using namespace std; int main() { int year; bool leap; cout
<< "请输入年份:" << endl; cin >> year; if ((year % 4 == 0 && year % 100 != 0) || (
year% 400 == 0)) leap = true; else leap = false; if (leap) cout << year << ' '
<< "is a leap year!" << endl; else cout << year << ' ' << "is not a leap year!"
<< endl; return 0; }