日期累加(北京理工大学考研机试题)
【摘要】
文章目录
日期累加日期类问题必备函数AC代码
日期累加
本题链接:日期累加
本博客给出本题截图:
日期类问题必备函数
const int months[13] = {
...
日期累加
本题链接:日期累加
本博客给出本题截图:
日期类问题必备函数
const int months[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int is_leap(int year) // 闰年返回1,平年返回0
{
if (year % 4 == 0 && year % 100 || year % 400 == 0)
return 1;
return 0;
}
int get_days(int y, int m) // y年m月有多少天
{
if (m == 2) return months[m] + is_leap(y);
return months[m];
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
AC代码
代码解释:打印日期(华中科技大学考研机试)的基础上加上一点小优化即可:先一年一年的去数,如果不够一年的天数再一天一天的去数。这里跳过一整年的操作细节处理如下:如果这一天是2月29,因为明天必不可能有2月29,故我们可以让总天数减一,然后让日期变为3月1,如果这一天在1月1日 ~ 2月28日之间,我们需要判断当年是否为闰年(看是否会跳过2月29这一天),如果这一天在3月1日 ~ 12月31日,我们需要判断明年是否为闰年(看是否会跳过2月29这一天)
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int months[13] = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
int is_leap(int year)
{
if (year % 4 == 0 && year % 100 || year % 400 == 0)
return 1;
return 0;
}
int get_days(int y, int m)
{
if (m == 2) return months[m] + is_leap(y);
return months[m];
}
int get_year_days(int y, int m)
{
if (m <= 2) return 365 + is_leap(y);
return 365 + is_leap(y + 1);
}
int main()
{
int T;
cin >> T;
while (T -- )
{
int y, m, d, a;
cin >> y >> m >> d >> a;
if (m == 2 && d == 29) a --, m = 3, d = 1;
while (a > get_year_days(y, m))
{
a -= get_year_days(y, m);
y ++ ;
}
while (a -- )
{
if ( ++ d > get_days(y, m))
{
d = 1;
if ( ++ m > 12)
{
m = 1;
y ++ ;
}
}
}
printf("%04d-%02d-%02d\n", y, m, d);
}
return 0;
}
- 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
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
文章来源: chen-ac.blog.csdn.net,作者:辰chen,版权归原作者所有,如需转载,请联系作者。
原文链接:chen-ac.blog.csdn.net/article/details/121238100
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)