日期类问题

给两个日期怎么计算两者间的日期差数,其中还要考虑闰年。 闰年的判断规则是:当年数不能被100整除时若其能被4整除则为闰年,或者其能被400整除时也是闰年。有了这个规则,怎么写就简单了。

#include <stdio.h>
// 定义宏判断是否为闰年
#define ISYEAP(x) x%100 != 0 && x%4 == 0 || x%400 == 0 
int dayOfMonth[13][2] = {
	0, 0,
	31, 31,
	28, 29,
	31, 31,
	30, 30,
	31, 31,
	30, 30,
	31, 31,
	31, 31,
	30, 30,
	31, 31,
	30, 30,
	31, 31
};
struct Date {
	int day;
	int month;
	int year;
	void nextDay() {
		day++;
		if (day > dayOfMonth[month][ISYEAP(year)]) {
			day = 1;
			month++;
			if (month > 12) {
				month = 1;
				year++;
			}
		}
	}
};
int buf[5001][13][32];
int Abs(int x) {
	return x < 0 ? -x : x;
}
int main() {
	Date tmp;
	int count = 0; // 计算日期与0000年1月1日的天数差
	tmp.day = 1;
	tmp.month = 1;
	tmp.year = 0;
	while (tmp.year != 5001) {
		buf[tmp.year][tmp.month][tmp.day] = count;
		tmp.nextDay();
		count++;
	}
	int d1, m1, y1;
	int d2, m2, y2;
	while (scanf("%4d%2d%2d", &y1, &m1, &d1) != EOF) {
		scanf("%4d%2d%2d", &y2, &m2, &d2);
		printf("%d\n", Abs(buf[y2][m2][d2] - buf[y1][m1][d1]) + 1);
	}
	return 0;
}

从上面的代码可以看到buf是个三维数组而且还挺大的,所以我们把他定义为全局变量。如果将其定义在函数main中,那么函数所可以使用的栈空间将不足以提供如此庞大的内存,出现栈溢出。

有了这个模板,其他日期类的问题基本就可以解决了。

如给一个日期,输出星期几:

#include <stdio.h>
#include <string.h>
// 定义宏判断是否为闰年
#define ISYEAP(x) x%100 != 0 && x%4 == 0 || x%400 == 0 
int dayOfMonth[13][2] = {
	0, 0,
	31, 31,
	28, 29,
	31, 31,
	30, 30,
	31, 31,
	30, 30,
	31, 31,
	31, 31,
	30, 30,
	31, 31,
	30, 30,
	31, 31
};
struct Date {
	int day;
	int month;
	int year;
	void nextDay() {
		day++;
		if (day > dayOfMonth[month][ISYEAP(year)]) {
			day = 1;
			month++;
			if (month > 12) {
				month = 1;
				year++;
			}
		}
	}
};
int buf[3001][13][32];
char monthName[13][20] = {
	"",
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December"
};
char weekName[7][20] = {
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday"
};
int main() {
	Date tmp;
	int count = 0; // 计算日期与0000年1月1日的天数差
	tmp.day = 1;
	tmp.month = 1;
	tmp.year = 0;
	while (tmp.year != 3001) {
		buf[tmp.year][tmp.month][tmp.day] = count;
		tmp.nextDay();
		count++;
	}
	int d, m, y;
	char s[20];
	while (scanf("%d%s%d", &d, s, &y) != EOF) {
		for (m = 1; m <= 12; m++) {
			if (strcmp(s, monthName[m]) == 0) {
				break;
			}
		}
		int days = buf[y][m][d] - buf[2016][8][15];
		days++;
		printf("%s\n", weekName[(days%7 + 7) % 7]);
	}
	return 0;
}

感谢您的观看,对您有用就分享出去吧 !

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容