在生活中,我们经常会用到日历这个东西,但是大家知道日历这个他是如何显示出来的呢?今天libero就来教教大家经典的日历算法。
源码:
using namespace std; int main(int argc,char *argv[]) { //输入月,周几,输入年,月天数最大值 int month,day,year,monthMax; // cout<<"Please input year: "<<endl; // cin >> year; // cout<<"Please input month: "<<endl; // cin >> month; //懒得输入了,直接赋值 year = 2017; month = 3; //闰 平年判断,这没什么好说的了。 if(year%4==0||(year%100==0 && year%400==0)) //闰年 { //每个月天数判断 if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) monthMax=31; if(month==2) monthMax=29; if(month==4||month==6||month==9||month==11) monthMax=30; } if(year%4!=0)//平年 { //每个月天数判断 if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) monthMax=31; if(month==2) monthMax=28; if(month==4||month==6||month==9||month==11) monthMax=30; } //因为基姆拉尔森算法,一月算做上一年的十三月,二月算做上一年的十四月。 if(month==1||month==2) { month+=12; year--; } //基姆拉尔森计算取得当月日历中的一号是周几 (本程序核心算法) day=(2+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7;//算出这月一号周几 if(day==0) { day=7; } //界面显示 cout<<" 1 2 3 4 5 6 7 "<<endl<<"==========================="<<endl; for(int i=1; i<=day-1; i++) { cout<<" "; } for(int j=1; j<=monthMax; j++) { if(j<10) { cout<<" "<<j<<" "; } if(j>=10) { cout<<" "<<j<<" "; } if((j+day-1)%7==0) { cout<<endl; } if(j==monthMax) { cout<<endl; } } cout<<endl; return 0; }
?源码解析:本程序算法主要依赖基姆拉尔森算法,关于算法具体实现和推导,libero会在后续文章中陆续贴出。思路是先取得当前年月日,并判断出是闰年还是平年?,然后判断出这个月有几天?最后根据基姆拉尔森算法获取当月中的 一号是周几,有了周几这个索引值,可以很容易的循环遍历出这个月的日历表。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧