日期差值 问题 or 本页代码方法改进(日期差值 法二)
完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int IsInYear(int year); //判断是否为闰年 是闰年返回0 否则返回1
int daysInMonth(int year,int month); //计算一个月有多少天
int Yearweekday(int year); //每年第一天星期几 星期天用1表示 依次类推
int mouthweekday(int year,int month); //每月第一天星期几 星期天用1表示 依次类推
void printdate(int mouthweekday,int daysInMonth); //打印
int main()
{
int year,mouth;
printf("请输入想要显示的年份和月份:");
while(scanf("%d%d",&year,&mouth))
{
printdate(mouthweekday(year,mouth),daysInMonth(year,mouth));
printf("请输入想要显示的年份和月份:");
}
return 0;
}
int IsInYear(int year)
{
return ((year%4)&&(!(year%100))||(year%400));
}
int daysInMonth(int year,int month)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return 31;
case 4:
case 6:
case 9:
case 11: return 30;
case 2: return (29-IsInYear(year));
default: return 0;
}
}
int Yearweekday(int year)
{
//计算 公元[1年,year) 之间共有多少天
int sum=0;
for(int i=1;i<year;i++)
sum=sum+(366-IsInYear(i));
//计算所输年份第一天【1.1】是星期几
//星期天用1表示 依次类推
int weekday=(sum+1)%7+1;
return weekday;
}
int mouthweekday(int year,int month)
{
int mouthweekday=Yearweekday(year);
for(int i=0;i<month;i++)mouthweekday=(mouthweekday+daysInMonth(year,i))%7;
return mouthweekday;
}
void printdate(int mouthweekday,int daysInMonth)
{
printf("日 一 二 三 四 五 六 \n");
for(int i=0;i<mouthweekday;i++)
{
printf(" ");
}
for(int j=1;j<=daysInMonth;j++)
{
if(j<10){ if((j+mouthweekday)%7==0)
printf(" %d \n",j);
else
printf(" %d ",j);}
else{
if((j+mouthweekday)%7==0)
printf("%d\n",j);
else
printf("%d ",j);
}
}
printf("\n");
}