輸入年份和月份,展示當月月曆
#include <stdio.h>
/**
* 萬年曆
*/
//是否是閏年
int isLeap(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
return 1;
}
return 0;
}
//計算 從1900年1月1日開始 到指定年月經過了多少天
int getTotalDays(int year, int month)
{
int totalDays = 0;
for (int i = 1900; i < year; i++) //計算到year-1年共多少天
{
if (isLeap(i))
{
totalDays += 366;
}
else
{
totalDays += 365;
}
}
//計算year年的1到month月 共多少天
for (int m = 1; m <= month; m++)
{
if (m == 2)
{ // 2月
if (isLeap(year))
{
totalDays += 29;
}
else
{
totalDays += 28;
}
}
//每月30天的月份
else if (m == 4 || m == 6 || m == 9 || m == 11)
{
totalDays += 30;
}
//每月31天的月份
else
{
totalDays += 31;
}
}
return totalDays;
}
//計算星期(參數:1900年1月1日開始 經過多少天)
int getWeekDay(int totalDays)
{
return totalDays % 7;
}
//計算某月共多少天
int getMonthDays(int year, int month)
{
if (month == 2)
{ // 2月
if (isLeap(year))
{
return 29;
}
else
{
return 28;
}
}
//每月30天的月份
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
return 30;
}
//每月31天的月份
else
{
return 31;
}
}
//列印資訊
void print(int year, int month)
{
printf("--------%d 年 %d 月 月曆--------\n", year, month);
printf("日 一 二 三 四 五 六\n"); //列印星期
int totalDays = getTotalDays(year, month - 1); //從1900年1月1日開始到month-1月共多少天
int weekDay = getWeekDay(++totalDays); //計算第month月的第一天星期幾
int monthTotalDays = getMonthDays(year, month); //本月多少天
for (int i = 0; i < weekDay; i++)
{
printf(" ");
}
for (int i = 1; i <= monthTotalDays; i++)
{
if (totalDays % 7 == 6)
{
printf("%d\n", i);
}
else
{
if (i < 10)
{
printf("%d ", i);
}
else
{
printf("%d ", i);
}
}
totalDays++;
}
printf("\n");
}
int main()
{
print(2023, 2);
return 0;
}