这个是朋友托我打的,不属于ACM,但觉得挺有意思,所以就放到这里了,题目有两个要求,输出当1年1月1日到前年每月的1号隔了多少天,并输出这天是星期几,然后再按格式输出这一年12个月的公历日历。
是一个挺简单的模拟,就是有点小麻烦和小细节需要注意,下面是代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; struct Node { int y,m,d,day; }; Node start; void init() { start.y = 1; start.m = 1; start.d = 1; start.day = 1; } bool is_leap(int year) { if(year%400==0 || (year%4==0&&year%100 != 0))return true; else return false; } int day_of_month(int year,int m) { if(m==1||m==3||m==5||m==7||m==8||m==10||m==12) return 31; if(m==2) { if(is_leap(year)) return 29; return 28; } return 30; } Node tmp; int getday(Node now) { tmp = start; int ans = 0; bool flag = false; while(tmp.y<=now.y) { while(tmp.m <= 12) { while(tmp.d <= day_of_month(tmp.y,tmp.m)) { if(tmp.y==now.y&&tmp.m==now.m&&tmp.d==now.d) { flag = true; break; } tmp.d++; tmp.day++; if(tmp.day==8) { tmp.day = 1; } ///cout<<"year month day d:"<<tmp.y<<" "<<tmp.m<<" "<<tmp.d<<" "<<tmp.day<<endl; ans++; } if(flag) break; tmp.d = 1; tmp.m++; } if(flag) break; tmp.m = 1; tmp.y++; } return ans; } int main() { int nowyear; printf("请输入年数: "); scanf("%d",&nowyear); init(); Node now; now.y = nowyear; now.d = 1; int firstday[13]; int allday[13]; for(int i = 1; i <= 12; i++) { now.m = i; int res = getday(now); // printf("到%d年%d月1号共有%d天 ",nowyear,i,res); // printf("这天是星期%d ",tmp.day); firstday[i] = tmp.day; allday[i] = day_of_month(nowyear,i); // puts(""); } printf("今年的日历为: "); for(int i = 1; i <= 12; i++) { printf(" %d月 ",i); printf("----------------------- "); ///printf(" 7 1 2 3 4 5 6 "); printf(" 日 一 二 三 四 五 六 "); int key = firstday[i]; ///cout<<"key = "<<key<<endl; if(key < 7) { for(int j = 1;j <= key;j++) cout<<" "; } int tot = 1,k1 = key==7?7:7-key,k0 = 0; bool mark = false; while(tot <= allday[i]) { printf("%3d",tot); k0++; tot++; if(k0==k1 && !mark) { puts(""); k0 = 0; mark = true; } if(mark&&k0==7) { puts(""); k0 = 0; } } puts(""); } return 0; }