这类题属于比较麻烦的一种题
一年中每个月有多少天(注意闰年的判断):
void m2days(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
days[2] = 29;
else days[2] = 28;
}
int days[15] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
此外,一般第一年,第一个月,最后一年,最后一个月都是需要特殊考虑的情况
日期差值
#include <time.h>
#include <iostream>
using namespace std;
int days[15] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void month2day(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
days[2] = 29;
else days[2] = 28;
}
int main() {
#ifdef SUBMIT
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int date1, date2;
while (cin >> date1 >> date2) {
int y1 = date1 / 10000, m1 = date1 / 100 % 100, d1 = date1 % 100;
int y2 = date2 / 10000, m2 = date2 / 100 % 100, d2 = date2 % 100;
int ans = 0;
month2day(y1);
if (y1 == y2) {
if (m2 == m1) {
ans += d2 - d1;
}
else {
ans += days[m1] - d1;
for (int i = m1 + 1; i < m2; i++) {
ans += days[i];
}
ans += d2;
}
}
else {
ans += days[m1] - d1;
for (int i = m1 + 1; i <= 12; i++) {
ans += days[i];
}
for (int i = y1 + 1; i < y2; i++) {
month2day(i);
for (int j = 1; j <= 12; j++) {
ans += days[j];
}
}
month2day(y2);
for (int i = 1; i < m2; i++) {
ans += days[i];
}
ans += d2;
}
cout << ans + 1 << endl;
}
#ifdef SUBMIT
long _end_time = clock();
printf("\n\ntime = %ld ms", _end_time - _begin_time);
#endif
return 0;
}
日期累加
#include <time.h>
#include <iostream>
using namespace std;
int days[15] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void m2days(int y) {
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
days[2] = 29;
else days[2] = 28;
}
int main() {
#ifdef SUBMIT
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int m;
cin >> m;
while (m--) {
int y, m, d, ds;
cin >> y >> m >> d >> ds;
int y1 = y, m1 = m, d1 = d;
m2days(y);
if (ds >= days[m] - d + 1) { // 注意+1,到下一个月
ds -= days[m] - d + 1;
d = 1;
m = (m + 1) % 13; // 注意是%13
if (m == 0) {
m = 1;
y++;
}
}
else {
d += ds;
ds = 0;
}
while (ds > 0) {
m2days(y);
int nextm = (m + 1) % 13;
if (ds >= days[m]) {
d = 1;
ds -= days[m];
m = nextm;
if (m == 0) {
m = 1;
y++;
}
}
else {
d = ds + 1; // 注意+1
ds = 0;
}
}
printf("%d-%02d-%02d\n", y, m, d);
}
#ifdef SUBMIT
long _end_time = clock();
printf("\n\ntime = %ld ms", _end_time - _begin_time);
#endif
return 0;
}