Can somebody help me figure out why this program can't add days to a date?

This program needs to add days to a date. 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
  #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;
}
Line 19: How many times will that execute for dd = n?

Ans:

once for each i < leftoverdays, again for i== leftoverdays, right? So even if dd == 0, and leftoverdays == 0, it will still run the block once.

Not a difficult fix. . .
Last edited on
closed account (SECMoG1T)
1
2
int dd = 1; //number of days to add /// dd=1???
 addyears = dd/365; //// 1/365 ? I am not sure of these  
Topic archived. No new replies allowed.