c中的一个月日历

时间:2013-02-15 16:55:29

标签: c calendar

我正在尝试在C中创建一个月的日历。此代码种类有效,但对于某些输入,间距是关闭的。我不太清楚如何修复它。

另外,如果你有办法让一个月的日历涉及的代码少于此,那就太好了,因为我必须在大约一个小时的时间里对它进行反复调查。

谢谢!

int main() {

    int spaces, days_in_month, day_of_week, i;

    printf("Please enter the numier of days in the month:\n");
    scanf("%d", &days_in_month);

    printf("Please enter starting day of the week:\n");
    scanf("%d", &day_of_week);

    spaces = day_of_week - 1;

    printf("Here's your calendar:\n");

    for (i=0; i<spaces; i++)
        printf("   ");


    for (i=1; i<=(7-spaces); i++)
        printf("  %d", i);

    printf("\n");

    if ((i-spaces) >10 && (i-spaces) < 14-spaces)
        printf("   ");

    for (i=(8-spaces); i<=(10-spaces); i++)
        printf("  %d", i);
    for (i=(11-spaces); i<=(14-spaces); i++)
        printf(" %d", i);

    printf("\n");

    for (i=(15-spaces); i<=(21-spaces); i++)
        printf(" %d", i);

    printf("\n");

    for (i=(22-spaces); i<=(28-spaces); i++)
        printf(" %d", i);

    printf("\n");

    for (i=(29-spaces); i<=days_in_month; i++)
        printf(" %d", i);

    return 0;

}

3 个答案:

答案 0 :(得分:3)

使用%2d代替%d,所以如果一天有数字1 ... 9,printf会为您插入一个空格。

答案 1 :(得分:2)

你的考试怎么样?

这是一种更简单的方法(忽略输入验证):

// Normalize day of week to be 0-6 rather than 1-7.
day_of_week -= 1;

// Pad the first line of the calendar.
for(i = 0; i < day_of_week; i++)
    printf("   ");

// For each day in the month...
for(i = 1; i <= days_in_month; i++)
{
    // Print the date for the current day_of_week.
    // '%3d' will print the value padding with spaces if necessary such that
    // at least 3 characters are written.
    printf("%3d", i);

    // Increment the day_of_week.
    // The modulo operator '% 7' will cause day_of_week to wrap around to 0
    // when day_of_week reaches 7.
    day_of_week = (day_of_week + 1) % 7;

    // if the new day_of_week is 0, output a newline to start at the
    // beginning of the next line.
    if(day_of_week == 0)
        printf("\n");
}

示例运行产生以下输出:

$ ./calendar.exe 
Please enter the numier of days in the month:
28
Please enter starting day of the week:
6
Here's your calendar:
                 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

答案 2 :(得分:1)

#include<stdio.h>

int main(void)
{
    int start_day, days_in_month, i, day_of_week;

    printf("Enter start day: ");
    scanf("%d", &start_day);

    printf("Enter days in month: ");
    scanf("%d", &days_in_month);

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

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