C program days between two dates

前端 未结 6 430
悲&欢浪女
悲&欢浪女 2021-01-02 18:30

I have written a program that should find the days between two dates, but it has some hiccups. The logic makes perfect sense in my head when I read through it, so

6条回答
  •  粉色の甜心
    2021-01-02 18:55

    Change

    int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    int daysPerMonthLeap[] = {31,29,31,30,31,30,31,31,30,31,30,31};
    

    to

    int daysPerMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int daysPerMonthLeap[] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
    

    i.e. pad the arrays at the beginning since all the code relies on the array values to start at element 1 rather than element 0.

    That will get rid of the error you complained of.

    The other problem is an off-by-one error when you add day2 to the total. In both cases you should add day2 - 1 rather than day2. This is also due to the date indexes starting at 1 instead of 0.

    After I made these changes (plus a couple just to get the code to compile), it works properly.

提交回复
热议问题