1

我制作了一个仅用于测试目的的程序,当您按住键盘上的“p”键时,它从 2012 年 1 月 1 日开始每天都会溢出,它应该会持续到 2013 年,尽管它会持续到 2013 年 1 月 32 日,这是一个我不知道如何解决的错误,我已经尝试解决这个问题几个小时了,但似乎没有什么可以让它正常工作..(应该在 31 日之后到 2013 年 2 月 1 日一月)

这是我的代码:

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


int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

int day = 0;
int year = 2012;

char *months[]=
{
    " ",
    " January ",
    " February ",
    " March ",
    " April ",
    " May ",
    " June ",
    " July ",
    " August ",
    " September ",
    " October ",
    " November ",
    " December "
};


int x = 1; //skip the blank element 0, get to January (element 1)

int main()
{

while(1)
{
    char ch;
    ch = getch(); //in_char();

    if(ch == 'p')
    {
        day++;


        if(day == month[x]+1)
        {
            day = 1; //day is equal to the first day of the new month
            month[x]++; //month data increments
            months[x]++; //month display increments
            x++; //element of month array increments to get the data of the next month


            if(year % 4 == 0) //leapyear
            {
                month[2] = 29;
            }
            else
            {
                month[2] = 28;
            }


            if(x == 13) //if 12 months have passed
            {
                year++; //year increments
                day = 1; //initialize day to be day 1 of the next year
                x = 1; //go back to the 'January' element in the array

                if(day == month[x]) //if day is equal to the first month (January) 31 days
                {
                    day = 1;
                    month[x]++; //month data increments
                    months[x]++; //month display increments
                }
            }
        }
        if(year == 9999)
        {
            year = 1;
        }


        printf("%i%s%04i\n",day,months[x],year);
    }
}


return 0;
}

输出:

.
.
.
28 December 2012
29 December 2012
30 December 2012
31 December 2012
1January 2013
2January 2013
3January 2013
4January 2013
5January 2013
6January 2013
7January 2013
8January 2013
9January 2013
10January 2013
11January 2013
12January 2013
13January 2013
14January 2013
15January 2013
16January 2013
17January 2013
18January 2013
19January 2013
20January 2013
21January 2013
22January 2013
23January 2013
24January 2013
25January 2013
26January 2013
27January 2013
28January 2013
29January 2013
30January 2013
31January 2013
**32January 2013**
1February 2013
2February 2013
.
.
.
4

1 回答 1

2

问题在这里:

    if(day == month[x]+1)
    {
        day = 1; // reset date...OKAY
        month[x]++; // NOT OKAY

通过这样做month[x]++,您正在增加该月允许的天数。相反,您需要保留一个变量来跟踪月份,就像您对日和年所做的那样。

于 2012-12-09T16:24:58.690 回答