Program to add days to a date giving me problems

I need to implement this into a larger program but I created a separate program to get the algorithm right. I'm running into problems. For instance when I add one day it added 2 days to the date and when I added 800 days I got 2/1/2017 instead of 1/31/2017 and I can't figure out what I'm doing wrong.


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
29
30
31
32
33
34
35
36
37
  #include <iostream>
using namespace std;

int main ()
{
        int day = 23, month = 11, year = 2014;
        int monthdays[] = {31,28,31,30,31,30,31,31,30,31,30,31};   //array holding # of 
                                                                                                       //days per month
        int addyears;    //number of years to add
        int leftoverdays; //days leftover after dividing by 365
        int dd = 1;    //number of days to add

        addyears = dd/365;
        leftoverdays = dd%365;

        year += addyears;

        for (int i = 0; i <= leftoverdays; i++)
                if (day < monthdays [month -1])
                        day ++;
                else if ((day == monthdays [month-1]) && (month < 12))
                {
                        day = 1;
                        month ++;
                }
                else if ((day == monthdays [month-1]) && (month == 12))
                {
                        day = 1;
                        month = 1;
                        year ++;
                }
                else
                        cout << "Error setting date!";

        cout << "NEW DATE: " << month << "/" << day << "/" << year << endl;
}
Last edited on
Topic archived. No new replies allowed.