C語言_日曆
阿新 • • 發佈:2018-11-04
編寫一個日曆程式,以2000年為基準,要求輸入一個年月,輸出對應月份的日曆表
執行結果:
程式碼如下:
#include <stdio.h> #include <stdlib.h> #include <assert.h> int month_day_num[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 IsLeapYear (int year) //判斷是不是閏年 { return ((year%4==0&&year%100!=0) || (year%400==0));//是閏年返回1,不是閏年返回零 } //求一年的第一天是星期幾,以2000年為基準(2000年第一天是星期六) int first_day_of_year(int year) { int i = 0; int day_num = 0; assert (year > 2000); for (i=2000; i<year; i++) { day_num += (365+IsLeapYear (i)); } return ((day_num+6)%7); } //求某一年的某一月第一天是星期幾 int first_day_of_month(int year, int month, int first_day) { int i = 0; int day_num = 0; assert (month>0 && month<13); for (i=1; i<month; i++) { day_num += month_day_num[IsLeapYear (year)][i]; } return (day_num+first_day)%7; } void print(int year, int month) { int i = 0; int first_day = first_day_of_month(year, month, first_day_of_year(year)); printf ("%d年%d月:\n", year, month); printf ("一\t二\t三\t四\t五\t六\t天\n\n"); for (i=0; i<first_day-1; i++) { printf ("\t"); } for (i=0; i<month_day_num[IsLeapYear(year)][month]; i++) { printf ("%d\t", i+1); if ((i+first_day)%7 == 0) { printf ("\n\n"); } } printf ("\n"); } int main() { int year = 0; int month = 0; printf ("請按以下格式輸入年月:year/month:"); scanf ("%d/%d", &year, &month); printf("\n"); print(year, month); system ("pause"); return 0; }