C语言 打印日历

目标:

根据输入的年份和月份来输出该年月的日历。

提示:

日历的格式如下图所示:
在这里插入图片描述

编程实现:

// 包含两种I/O库,可以使用任一种输入输出方式
#include <stdio.h>
#include <iostream>
// 函数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;
        else
            w += 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;
        else
            w += 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   2
   3   4   5   6   7   8   9
  10  11  12  13  14  15  16
  17  18  19  20  21  22  23
  24  25  26  27  28  29  30
  31

猜你喜欢

转载自blog.csdn.net/m0_66411584/article/details/127625738