码迷,mamicode.com
首页 > 编程语言 > 详细

日历问题(c++实现)

时间:2015-07-30 22:52:58      阅读:491      评论:0      收藏:0      [点我收藏+]

标签:

描述:在我们现在使用的日历中, 闰年被定义为能被4整除的年份,但是能被100整除而不能被400整除的年是例外,它们不是闰年。例如:1700, 1800, 1900 和 2100 不是闰年,而 1600, 2000 和 2400是闰年。 给定从公元2000年1月1日开始逝去的天数,你的任务是给出这一天是哪年哪月哪日星期几。

输入:输入包含若干行,每行包含一个正整数,表示从2000年1月1日开始逝去的天数。输入最后一行是−1, 不必处理。可以假设结果的年份不会超过9999。

输出:对每个测试样例,输出一行,该行包含对应的日期和星期几。格式为“YYYY-MM-DD DayOfWeek”, 其中 “DayOfWeek” 必须是下面中的一个: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" and "Saturday“。

input:

1730 
1740 
1750 
1751 
-1

output:
2004-09-26 Sunday 
2004-10-06 Wednesday 
2004-10-16 Saturday 
2004-10-17 Sunday

分析:难点是年月日的判断,我们可以用这样一种方法来计算,首先计算年份,最开始为2001,剩余天数为n,如果n大于该年的天数,年数加一,同时剩余天数减去该年天数,知道剩余天数小于该年天数,即可确定年份。同样的方法确定月份。最后剩余天数加1就是日期。星期的判断在2000年1月1日的星期基础上加n%7。
 1 #include<iostream>
 2 #include<iomanip>
 3 using namespace std;
 4 
 5 int yearDays(int year)                                                //返回该年的天数
 6 {
 7     if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
 8         return 366;
 9     else
10         return 365;
11 }
12 
13 int monthDays(int year, int month)                                        //返回对应月份天数
14 {
15     switch (month)
16     {
17     case 1:return 31;
18     case 2:
19         if (yearDays(year) == 365)
20             return 28;
21         else
22             return 29;
23     case 3:return 31;
24     case 4:return 30;
25     case 5:return 31;
26     case 6:return 30;
27     case 7:
28     case 8:return 31;
29     case 9:return 30;
30     case 10:return 31;
31     case 11:return 30;
32     case 12:return 31;
33     }
34 }                                                    
35 void cal(int n, int &year, int &month, int &day)            //计算年月日
36 {
37     year = 2000;
38     while (n >= yearDays(year))
39     {
40         n -= yearDays(year);
41         year++;
42     }
43     month = 1;
44     while (n >= monthDays(year,month))
45     {
46         n -= monthDays(year, month);
47         month++;
48     }
49     day = n+1;
50 }
51 void week(int n)                                    //计算星期几
52 {
53     int week = n % 7;
54     switch (week)
55     {
56     case 0:cout << "Saturday"; break;
57     case 1:cout << "Sunday"; break;
58     case 2:cout << "Monday"; break;
59     case 3:cout << "Tuesday"; break;
60     case 4:cout << "Wednesday"; break;
61     case 5:cout << "Thursday"; break;
62     case 6:cout << "Friday";
63     }
64 }
65 
66 int main()
67 {
68     int n,year,month,day;
69 
70     while ((cin >> n) && (n != EOF))
71     {
72         n;
73         cal(n, year, month, day);
74         cout << year << "-" <<setw(2)<<setfill(0)<< month << "-" <<setw(2)<<setfill(0)<< day << " ";
75         week(n);
76         cout << endl;
77     }
78     system("pause");
79     return 0;
80 }

 

日历问题(c++实现)

标签:

原文地址:http://www.cnblogs.com/wuyoucao/p/4690594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!