开发者

infinite loop while counting dates

I'm trying to solve problem that asks to find how many times 13th day occurs at each weekday in period of 1990+N-1 years.

int weekDay = 1;
int week[] = {0,0,0,0,0,0,0};

N = 20;

for (int year = 1990; year <= 1990+N-1; year++){
    for (int month = 1; month <= 12; month++){
        int days = numberOfDays(year,month);

        for (int day = 1; day <= days; day++){
            if (day == 13)
                week[weekDay] += 1;

            weekDay += 1;
            if (weekDay > 7)
                weekDay = 1;
        }
    }
}

Here's my solution, however I get stuck in an infinite loop in year and can't seem to fix it.

EDIT : numberOfDays function.

int numberOfDays(int year, int month)
{
    if (month == 2 && leapYear(year))
        return 29;
    else if (month == 2)
        return 28;

    if (month == 9 || month == 4 || mon开发者_如何学Goth == 6 || month == 11)
        return 30;

    return 31;
}


You are using weekdays in the range 1..7 but your histogram array week[] is indexed 0..6.


One possible solution - change:

            week[weekDay] += 1;

to:

            week[weekDay - 1] += 1;

Another solution - make week[] one element bigger and don't use element 0, i.e. change:

int week[] = {0,0,0,0,0,0,0};

to:

int week[] = {0,0,0,0,0,0,0,0};

A third possible solution - use week days in the range 0..6, i.e. change:

int weekDay = 1;

to:

int weekDay = 0;

and change:

        if (weekDay > 7)
            weekDay = 1;

to:

        if (weekDay > 6)
            weekDay = 0;


Off-by-one. Your week[] array has 7 elements, indexed 0..6. You write to week[7], which overwrites something you didn't intend, such as e.g. the year variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜