全知全能を目指す人のありがたい雑記

何かしら意味のあるありがた~い話か、意味のない雑念だらけの日記を書く予定です。

C言語でうるう年計算・月の末日計算・曜日計算を一通り書いた

学生の課題あるあるのプログラム。

各関数は全部落ちてるソースをパクっただけ。

fudebaco.com
edu.clipper.co.jp
C言語入門:うるう年判定プログラム:Geekなぺーじ

#include <stdio.h>

int main(void){
    int year; //yyyyで入力する!例「1970」
    scanf("%d", &year);
    
    int month; //mmで入力する!例「01」
    scanf("%02d", &month);
    
    char weekdays[7][4] = {"日","月","火","水","木","金","土"};
    
    int lastday = GetLastDay(year, month);
    
    for(int today = 1; today < lastday + 1; ++today){
        printf("%02d%02d%02d日 ",year,month,today);
        int weekday = GetWeekday(year, month, today);
        printf("%s曜日\n",weekdays[weekday]);
    }
    return 0;
}

int IsLeapYear(int year){
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
      printf("%02d年はうるう年\n", year);
      return 1;
    } else {
      printf("%02d年はうるう年ではない\n", year);
      return 0;
    }
}

int GetWeekday( int y, int m, int d ){
    if( m < 3 ) {
        y--; m += 12;
    }
    return ( y + y/4 - y/100 + y/400 + ( 13*m + 8 )/5 + d )%7;
}

int GetLastDay(int year, int month){
    int l;
    int lmdays[] = {31,29,31,30,31,30,31,31,30,31,30,31};
    int mdays[]  = {31,28,31,30,31,30,31,31,30,31,30,31};
    int lastday;
    
    l = IsLeapYear(year);
    if (l == 1) {
        lastday = lmdays[month - 1];
    } else {
        lastday = mdays[month - 1];
    }
    
    printf("%02d%02d月の末日は%d\n",year,month,lastday);
    return lastday;
}

入力

1992 02

出力

1992年はうるう年
1992年02月の末日は29日
1992年02月01日 土曜日
1992年02月02日 日曜日
1992年02月03日 月曜日
1992年02月04日 火曜日
1992年02月05日 水曜日
1992年02月06日 木曜日
1992年02月07日 金曜日
1992年02月08日 土曜日
1992年02月09日 日曜日
1992年02月10日 月曜日
1992年02月11日 火曜日
1992年02月12日 水曜日
1992年02月13日 木曜日
1992年02月14日 金曜日
1992年02月15日 土曜日
1992年02月16日 日曜日
1992年02月17日 月曜日
1992年02月18日 火曜日
1992年02月19日 水曜日
1992年02月20日 木曜日
1992年02月21日 金曜日
1992年02月22日 土曜日
1992年02月23日 日曜日
1992年02月24日 月曜日
1992年02月25日 火曜日
1992年02月26日 水曜日
1992年02月27日 木曜日
1992年02月28日 金曜日
1992年02月29日 土曜日