基础:已知某天的日期求下一天的日期
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
using namespace std;
void NextDay(int &year, int &month, int &day) {
//存储一下 月份和天数的对应关系
int dayOfMonth[] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int isLeap; //是否闰年
isLeap = year % 400 == 0 || year % 4 == 0 && year % 100 != 0;//1900不是闰年
if (isLeap) {
dayOfMonth[2] = 29;
}
else {
dayOfMonth[2] = 28;
}
++day;
if (day > dayOfMonth[month]) {
day = 1;
++month;
}
if (month > 12) {
month = 1;
++year;
}
//printf("NextDay year = %d, month = %d, day = %d\n", year, month, day);
}
int main() {
int year = 1900;
int month = 2;
int day = 28;
NextDay(year,month,day);
return 0;
}
问题一:给定日期,求是今天的第几天
- 连续调用NextDay()函数,并用计数器count记录
int main() {
int year, month, day;
while (scanf("%d%d%d", &year, &month, &day) != EOF) {
int count = 1;
int curmonth = 1;
int curday = 1;
while (1) {
if (month == curmonth && day == curday) {
break;
}
NextDay(year, curmonth, curday);
++count;
}
printf("%d\n", count);
}
return 0;
}
问题二:打印日期
int main() {
int year, n;
while (scanf("%d%d", &year, &n) != EOF) {
int next = 1;
int curmonth = 1;
int curday = 1;
while (1) {
if (next == n) {
break;
}
NextDay(year, curmonth, curday);
++next;
}
printf("%04d-%02d-%02d\n", year, curmonth, curday);
}
}
问题三:日期累加
int main() {
int m;
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int curyear, curmonth, curday, total;
int next = 0;
scanf("%d%d%d%d", &curyear, &curmonth, &curday, &total);
while (next < total) {
NextDay(curyear, curmonth, curday);
++next;
}
printf("%04d-%02d-%02d\n", curyear, curmonth, curday);
}
}