1

我正在尝试用 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;

}
4

3 回答 3

3

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

于 2013-02-15T17:10:26.010 回答
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
于 2013-02-15T19:19:33.503 回答
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;
}
于 2015-07-13T17:02:04.843 回答