1// 给定一个天数,查询该天之后的日期
2//例如
3//当前日期是 2008 11 10 则5050天后是 2022 9 8
4
5#include <iostream>
6
7using namespace std;
8
9class DAY
10{
11private:
12    int y;
13    int m;
14    int d;
15    int days[12];
16
17public:
18    DAY()
19    {
20        cout<<"请输入当前日期"<<endl;
21        cout <<"year"<<endl;
22        cin >> y;
23        cout << "mouth"<<endl;
24        cin >>m;
25        cout << "day"<<endl;
26        cin >> d;
27
28        int i;
29
30        for( i = 1 ; i <= 12 ; i++)
31        {
32            switch(i)
33            {
34
35            case 2:
36                days[i-1= isLeapYear() ? 29:28//设置2月天数
37                break;
38
39            case 4:
40            case 6:
41            case 9:
42            case 11:
43                days[i-1= 30;
44                break;
45
46            default :
47                days[i-1= 31;
48            }

49        }

50    }

51
52    void show()
53    {
54        cout <<"year:"<<y<<endl;
55        cout <<"mouth:"<<m<<endl;
56        cout <<"day:"<<d<<endl;
57    }

58
59    int judge_day(int mouth)
60    {
61        return days[mouth-1];
62    }

63
64    void calculate(int increase)
65    {
66        if(d + increase <= days[m-1])
67            d += increase;
68        else
69        {
70            increase -= days[m-1- d;
71            m++;
72
73            if(m>12)
74            {
75                //if m is greater than 12 , and increase is less than days[m-1]
76                //,then the following while statement will not be executed,
77                //so must reset m and year++
78
79                m = 1;
80                y++;
81            }

82
83            while(increase -days[m-1>0)
84            {
85                increase -= days[m-1];
86                m++;
87
88                if(m > 12)
89                {
90                    y++;
91                    m = 1;
92
93                    days[1= isLeapYear() ? 29 : 28;
94                }

95            }

96
97            d = increase;
98        }

99    }

100
101    bool isLeapYear()
102    {
103        return ( y%4 == 0 && y%100 != 0 ) || (y%400 == 0);
104    }

105}
;
106
107int main()
108{
109    DAY test;
110    int increase;
111
112    test.show();
113
114    cout <<"请输入天数,以查询该天之后的日期"<<endl;
115    cin >> increase;
116
117    test.calculate(increase);
118    cout <<"\n"<<increase<<"天以后是:"<<endl;
119    test.show();
120
121    return 0;
122}

posted on 2008-12-11 22:03 zhaoyg 阅读(412) 评论(1)  编辑 收藏 引用 所属分类: 小代码

# re: 计算日期 2008-12-11 22:05 | 908971