编写程序,要求根据用户输入的年月,打印出该月份的日历

日期差值 问题 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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隔壁de小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值