判断闰年(七)

来源:互联网 发布:打的软件叫车 编辑:程序博客网 时间:2024/06/11 16:01

闰年的一个基本规则是:四年一闰,百年不闰,四百年再闰。通俗一点就是:能够被4整除,但同时不能被100整除却能被400整除的年份就叫闰年。

这里面最关键的一句代码就是:

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)

【代码示例】

#include <iostream>#include <stdlib.h>using namespace std;int LeapYear(int year){if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){return 1;}else{return 0;}}int main(){//std::cout.setf(std::ios::fixed,std::ios::floatfield);//十进制计数法,不是科学计数法//std::cout.precision(2);//保留2位小数int begin_year,end_year;int num=0;cout << "\n\n\t\t\t\t\t请输入你要查询的年份时间段:\n";cout << "\t\t\t\t\t\tbegin_year:";cin >> begin_year;cout << "\t\t\t\t\t\tend_year:";cin >> end_year;cout << "\n\t\t\t\t\t请输出从"<<begin_year<<"年"<<"至"<<end_year<<"年之间所有的闰年年份:\n";for(begin_year; begin_year <= end_year; begin_year++ ){if (LeapYear(begin_year) == 1){cout << begin_year << " ";num++;}}cout << "\n\t\t\t\t\t该年份时间段一共有"<<num<<"个年份是闰年!\n";system("pause");return 0;}
【演示结果】





原创粉丝点击