c語言編寫程式“輸入任意一個年份和月份,列印當月日曆。”
阿新 • • 發佈:2019-02-19
日常生活中我們所見到的日曆如圖所示:
程式碼思路:
1. 我們想列印某年某月的日曆,我們就得知道這個月是從星期幾開始,且這個月有多少天。
2. 要想知道這個月是從星期幾開始的,就得知道上一個月的最後一天是星期幾,要想知道上一個月的最後一天是星期幾,就得知道上一個月是星期幾開始的,以此推類,我們就需要定義一個基準年以及基準年是從星期幾開始的。
後面的程式碼,我們定義基準年為2000年,且定義2000年是從星期六開始的
3. 然後計算你想知道的這個年份是從星期幾開始的,以及月份是從星期幾開始的,並實現列印。
程式碼:
1. 主函式
首先輸入你想列印哪一年哪一月的日曆, 其次計算這一個年份是從星期幾開始的,在計算月份是星期幾開始的;
2.其次定義一個全域性的陣列變數,用於存放每個月的天數。
由於年份有閏年,平年,mon[1]代表平年,mon[2]代表閏年;
3. first_ day_ of _year函式
其中isleap函式:
4. first_ day _ of_month函式
5. show展示函式
參考程式碼:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
mon[2][13] = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31 , 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
//判斷閏年
int isleap(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return 1;
else
return 0;
}
//年份的第一天
int first_day_of_year(int year)
{
int base_year = 2000; //定義一個基準年2000年
int first_day = 6; //基準天:2000年1月1號是星期6
int i = 2000;
int total = 0; //天數總和
for (i = base_year; i < year; i++)
{
total = total + 365 + isleap(i); //isleap函式用於判斷年份是否是閏年,如果是返回1,不是返回0
}
return (total+first_day)%7;
}
//月份第一天
int first_day_of_month(int year, int month, int first_year)
{
int total = 0; //天數和
int i = 0;
for(i = 1; i < month; i++)
{
total = total + mon[isleap(year)][i];
}
return (total + first_year) % 7;
}
//展示日曆
void show(int year,int month, int first_month)
{
int i = 0;
printf("一 二 三 四 五 六 日\n");
for (i = 0; i < first_month-1; i++)
{
printf(" "); //月份第一天是從first_month開始的,所以首先列印first_month-1個空格
}
for (i = 1; i <= mon[isleap(year)][month]; i++)
{
printf("%-5d", i);
if ((first_month-1+i) % 7 ==0) //如果(數字+空格數)%7==0,則換行
printf("\n");
}
printf("\n");
}
int main()
{
int year, month;
printf("年/月:"); //輸入你想列印的年份
scanf("%d/%d", &year, &month);
int first_year = first_day_of_year(year);//年份第一天
int first_month = first_day_of_month(year, month, first_year);//月份第一天
show(year, month, first_month);
system("pause");
return 0;
}
執行:
對照日曆: