演習5-9 K&R プログラミング言語C

演習5-9

#include <stdio.h>
#include <stdlib.h>

int day_of_year(int, int, int);
int month_day(int, int, int*, int*);

static char daytab[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 main(void)
{
    int m, d;

    printf("2009/3/1 => %d\n", day_of_year(2009, 3, 1));
    month_day(2009, 60, &m, &d);
    printf("60 => %d/%d/%d\n", 2009, m, d);

    return 0;
}

/* day_of_year : 月と日から年内の通算日を求める */
int day_of_year(int year, int month, int day)
{
    int i, leap;

    leap = (year%4 == 0 && year%100 != 0) || (year%400 == 0);
    if (month > 12 || month < 1 || day > *(*(daytab + leap) + month) || day < 1) {
        fprintf(stderr, "DAY_OF_YEAR : ERROR\n");
        return EXIT_FAILURE;
    }
    for (i = 1; i < month; i++)
        day += *(*(daytab + leap) + i);
    return day;
}

/* month_day : 年の通算日から月と日を求める */
int month_day(int year, int yearday, int *pmonth, int *pday)
{
    int i, leap;

    leap = (year%4 == 0 && year%100 != 0) || (year%400 == 0);
    if (yearday > 365 + leap || yearday < 1) {
        fprintf(stderr, "MONTH_DAY : ERROR\n");
        return EXIT_FAILURE;
    }
    for (i = 1; yearday > *(*(daytab + leap) + i); i++)
        yearday -= *(*(daytab + leap) + i);

    *pmonth = i;
    *pday = yearday;
    return 0;
}

実行結果

$ ./ex5-9
2009/3/1 => 60
60 => 2009/3/1
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»