c中的日历与最后一行的总和

时间:2013-02-19 21:25:33

标签: c arrays calendar sum

我正在尝试制作一个月打印最后几天总和的日历。

此输出对于日历是正确的,但是总和会一直打印出来为0.对于3 = day_of_week和30 = days_in_month的输入,总和应为26 + 27 + 28 + 29 + 30 = 140

感谢。

int main() {

int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;

printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);

printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);

for (i=0; i<3*day_of_week; i++)
    printf(" ");

for (i=1; i<=days_in_month; i++) {

    printf("%3d", i);
    array[i] = i;

    day_of_week++;

    if (day_of_week%7==0){
        printf("\n");
    }

}
    printf("\n");
    for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
        sum+=array[a];

printf("sum of last row is %d\n", sum);


return 0;

}

3 个答案:

答案 0 :(得分:1)

你有

for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)

day_of_week在您的程序中不会保持不变,并且在使用此语句之前会更改:

day_of_week++;

day_of_week后使用第二个变量递增而不修改scanf

答案 1 :(得分:1)

这里有一个问题:

for (i=1; i<=days_in_month; i++) {

    printf("%3d", i);
    array[i] = i;

    day_of_week++;

    if (day_of_week%7==0){
        printf("\n");
    }

}

您允许day_of_week超出范围。您的代码期望该值不超过7.此循环将导致该变量设置为用户输入的值加上(days_in_month - 1)。在最后的for循环中,语句7 - day_of_week可能会为负数,这会导致其余代码丢失。

当您测试变量modulo 7并打印换行符时,您会检查溢出。执行此操作时,也请设置day_of_week = 0

此外,只要您从用户那里获得输入,就计算(days_in_month-(7-day_of_week))并将其存储在临时变量中。由于您在代码中操作这些变量,因此最终的for循环可能没有使用您认为正在使用的值。或者,不要修改用于用户输入的变量,并创建其他变量以用作临时变量。

答案 2 :(得分:1)

我不明白为什么你这么做 ++ day_of_week

这样的事情会更好:

int main()
{
    int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;

    printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri,     7=sat\n");
    scanf("%d", &day_of_week);

    printf("Enter the number of days in this month:\n");
    scanf("%d", &days_in_month);

    for (i = 0; i < 3 * day_of_week; i++)
        printf(" ");
    for (i = 1; i <= days_in_month; i++)
    {
        printf("%3d", i);
        array[i] = i;
        if (i % 7 == 0)
            printf("\n");
    }
    printf("\n");
    for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
        sum+=array[a];
    printf("sum of last row is %d\n", sum);
    return 0;
}