C语言 打印日历
目标:
根据输入的年份和月份来输出该年月的日历。
提示:
日历的格式如下图所示:

编程实现:
// 包含两种I/O库,可以使用任一种输入输出方式
#include
#include
// 函数printMonth:按要求的格式打印某年某月的日历
// 参数:year-年,month-月
// 返回值:无
void printMonth(int year, int month);
// leapYear:判断闰年
// 参数:y-年
// 返回值:1-是闰年,0-不是闰年
int leapYear(int y)
{if(y % 400 == 0||y % 4 == 0 && y % 100 != 0)return 1;return 0;
}// 函数whatDay:计算某年某月的1号是星期几
// 参数:year-年,month-月
// 返回值:1到7--星期1到星期日
int whatDay(int year, int month)
{// 1年月日是星期一int w = 1;int i;// 1到year-1都是全年for(i = 1; i < year; i++){if(leapYear(i))w += 366;elsew += 365;}switch(month){case 12: // 加月的w += 30;case 11: // 加月的w += 31;case 10: // 加月的w += 30;case 9: // 加月的w += 31;case 8: // 加月的w += 31;case 7: // 加月的w += 30;case 6: // 加月的w += 31;case 5: // 加月的w += 30;case 4: // 加月的w += 31;case 3: // 加月的if(leapYear(year))w += 29;elsew += 28;case 2: // 加月的天w += 31;case 1: // 1月不加了;}// 得到-6,其中为星期天w = w % 7;// 调整星期天if(w == 0)w = 7;return w;
}//现函数printMonth
void printMonth(int year, int month)
{printf(" 一 二 三 四 五 六 日\n"); //打印 int w=whatDay(year,month); //w-->星期几 int a[12]={31,28,31,30,31,30,31,31,30,31,30,31}; //月对应的日数 int n=a[month-1]; //n-->日数 if(leapYear(year)&&month==2){n++;} //如果是闰年2月+1日 int x=0; //定义一个变量x for(int i=1;i<w;i++){printf(" ");x++;} for(int i=1;i<=n;++i){printf("%4d",i);x++;if(x%7==0)printf("\n");}
}int main()
{// 年、月int y, m;// 输入年月scanf("%d %d",&y,&m);// 输出该年月的日历printMonth(y,m);return 0;
}
2022 10一 二 三 四 五 六 日1 23 4 5 6 7 8 910 11 12 13 14 15 1617 18 19 20 21 22 2324 25 26 27 28 29 3031
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
