step1 . day5 C语言基础练习之日历(使用函数调用,优化至元年开始时间)

尝试着优化了一下,不知道为什将基准时间1990-1-1改为0-1-1(都是周一)(此处错误,应该是1-1-1是周一,即公元元年是1年不是0年),输出结果都不对,查找了一下解决方案,有个函数可以计算出某天的是周几的返回值,就尝试使用函数传参调用了一下,竟然成功了,代码供大家参考一下:

#include <stdio.h>

int getWeekdayByYearday(int iY, int iM, int iD)
{
int iWeekDay = -1;
if (1 == iM || 2 == iM)
{
iM += 12;
iY--;
}
iWeekDay = (iD + 1 + 2 * iM + 3 * (iM + 1) / 5 + iY + iY / 4 - iY / 100 + iY / 400) % 7;
return iWeekDay;
}


void monthPrint(int year,int month){
int sum = 0;
int k,m;
int month_day=0;


if(month==1 || month==3 ||month==5 ||month==7 ||month==8 ||month==10 ||month==12)
month_day=31;

else if(month==4 ||month==6 ||month==9 ||month==11)
month_day=30;
else
{
if( (year%400==0) || ((year%100!=0) && (year%4==0)) )
month_day=29;
else
month_day=28;
}
printf("%d-%d\n",year,month);
printf("Mon\tTue\tWed\tThu\tFri\tSat\tSun\n");
for(k=1;k<getWeekdayByYearday(year,month,1);k++)
printf("\t");
for(m=1;m<=month_day;m++)
{
if((m+k-1)%7==0)
printf("%d\n",m);
else
printf("%d\t",m);
}
putchar('\n');
return;
}

void yearPrint(int year){
int i;
for(i=1;i<=12;i++){
monthPrint(year,i);
}
return;
}

int main(int argc, const char *argv[]){
int year,month;
int check_year,check_month;
printf("*******************please choose********************\n");
printf("************1.print a year's calendar***************\n");
printf("************2.print a month's calendar***************\n");
printf("*****************************************************\n");

int choose = 0;
printf("your choose is:");
scanf("%d",&choose);

/*
while((choose != 1) || (choose != 2)){
getchar();
printf("error input,choose again:");
scanf("%d",&choose);
 }

*/

switch(choose){
case 1 :printf("input year(xxxx):");
check_year = scanf("%d",&year);
while(year<0)
{
getchar();
printf("year error,input again:");
check_year = scanf("%d",&year);
}
yearPrint(year);
break;

case 2 :printf("input year-month(xxxx-xx):");
check_month = scanf("%d-%d",&year,&month);
while(2 > check_month || month < 1 || month > 12)
{
getchar();
printf("error,input again:");
check_month = scanf("%d-%d",&year,&month);
}
monthPrint(year,month);
break;
}
return 0;
}

posted @ 2019-07-01 21:58  灰机12321  阅读(207)  评论(0编辑  收藏  举报