计算机考研复试上机题 —— 日期累加 (北京理工大学)

 

思路:

  1. 了解闰年的判断方式,以及每个月拥有的天数,提前设置好年月日规则;

  2. 遍历跨度时间,按照日期规则记天数变化;

C++代码:

 1 #include<iostream>
 2 #include<stdio.h>
 3 
 4 using namespace std;
 5 
 6 //通过年份判断是否是闰年 
 7 int isLeapYear(int year);
 8 
 9 int isLeapYear(int year) {
10     //闰年成立条件 
11     if((year%4==0 && year%100!=0) || year%400==0) {
12         return 1;
13     }else {
14         return 0;    
15     }
16 }
17 
18 //十二个月中每个月的日期总数, days[0][]平年, days[1][]闰年 
19 int days[2][13] = {
20             {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
21             {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
22         };
23 
24 void solve() {
25     //span: 时间跳跃跨度 
26     int year, month, day, span;
27     cin>> year>> month>> day>> span;
28     //天数满了进位一月,月数满了进位一年 
29     while(span--) {
30         day++;
31         //isLeapYear()判断闰年返回1, 平年返回0 
32         if(day > days[isLeapYear(year)][month]) {
33             month++;
34             day = 1;
35             if(month > 12) {
36                 year++;
37                 month = 1;
38             }
39         }
40     }
41     //注意格式year-month-day, 比如2018年5月1日是 2018-05-01 
42     printf("%d-%02d-%02d\n", year, month, day);
43 }
44 
45 int main() {
46     int n;
47     cin>> n;
48     for(int i=0; i<n; i++) {
49         solve();
50     }
51     
52     return 0;
53 }

猜你喜欢

转载自www.cnblogs.com/Lunix-touch/p/12299814.html