用C格式化日历

时间:2015-10-05 17:37:51

标签: c calendar formatting dayofweek

我正在处理一个问题,我必须使用给定的信息格式化日历。我非常接近我的回答,但我无法弄清楚最后的小问题。这是我的代码:

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

int length(int month, int year);
int day_of_week(int day, int month, int year);
void print_calendar(int start_day, int month_length);

int main(void)
{
    int mon;
    int yr;

    for(;;) //infinite loop
    {
        printf("Enter a month(1=Jan, ..., 12=Dec): ");
        scanf("%d", &mon);

        if (mon <= 12 && mon >= 1) //if inside the range (1-12) break the loop
            break;
        else
            printf("Not a valid month.\n");
    }
    for(;;) //infinite loop
    {
        printf("Enter a year(>0): ");
        scanf("%d", &yr);

        if (yr > 0) //if the year is greater than zero
            break;
        else
            printf("Not a valid year.\n");
    }
    print_calendar(day_of_week(1,mon,yr), length(mon, yr));
}
int length(int month, int year)
{
    int monthday;

    if (month == 2)
    {
        if ((year % 400 == 0)||((year % 100 !=0) && (year % 4 == 0)))
        {
            monthday = 29;
        }
        else
        {
            monthday = 28;
        }
    }
    else
    {
        monthday = (30 + (month + (month/8))%2);
    }
    return monthday;
}

int day_of_week(int day, int month, int year)
{
    int k,j,h;
    if (month == 1)
    {
        month = 13;
        year--;
    }

    if (month == 2)
    {
        month = 14;
        year--;
    }

    k = year%100;
    j = year/100;
    h = day + 13*(month+1)/5 + k + k/4 + j/4 + 5*j;
    h = h%7;

    switch(h)
    {
        case 0: printf("Saturday\n"); break;
        case 1: printf("Sunday\n"); break;
        case 2: printf("Monday\n"); break;
        case 3: printf("Tuesday\n"); break;
        case 4: printf("Wednesday\n"); break;
        case 5: printf("Thursday\n"); break;
        case 6: printf("Friday\n"); break;
    }
    return 0;
}

void print_calendar(int start_day, int month_length)
{
    int i;

    for (i = 1; i < start_day; i++)
    {
        printf("   ");
    }

    for (i = 1; i <= month_length; i++)
    {
        printf("%2d ", i);
        if ((i + start_day - 1)%7 == 0)
        {
            printf("\n");
        }
    }
    return 0;
}

输出看起来有点像这样:

Enter a month(1=Jan, ..., 12=Dec): 1
Enter a year(>0): 2014
Wednesday
 1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

为什么1会像那样出现在顶部?我已经玩了一段时间,但我无法弄明白。提前谢谢。

1 个答案:

答案 0 :(得分:2)

day_of_week()始终返回0,所以此块:

for (i = 1; i < start_day; i++)
{
    printf("   ");
}

将执行0次,因为start_dayday_of_week()的输出