3.3 图形输出
[PAT B1036] 和奥巴马一起编程
3.4 日期处理
关于平年和闰年的知识
平年365天,闰年366天,多的一天是闰年才有的2.29。
不是整百年份只要能被4整除就是闰年,整百年需要被400整除才是闰年。
思路:逐日加,日超过月的限制就换到下个月第一天,月超过年的限制,就换到下一年第一个月第一天。本质上还是简单模拟,但是细节多了很多。要优化的话可以先把年份加到t2y-1年,如果加到t2y年可能日期直接超出。
还有需要注意的是细节,比如说取余号和除号要分清楚。
代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
int month[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} };
int isLeap(int y) {
return ((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0));
}
int main() {
int t1, t2;
int t1y, t2y, t1m, t2m, t1d, t2d;
int count;
while (~scanf("%d%d",&t1,&t2)) {
count = 1;
if (t2 < t1) swap(t1, t2);//t1小于t2
t1y = t1 / 10000; t2y = t2 / 10000;
t1m = t1 % 10000 / 100;t2m = t2 % 10000 / 100;
t1d = t1 % 100; t2d = t2 % 100;
while (t1y < t2y || t1m < t2m || t1d < t2d) {
t1d++;
if (t1d == month[t1m][isLeap(t1y)]+1) {
t1m++;
t1d = 1;
}
if (t1m == 13) {
t1y++;
t1m = 1;
}
count++;
}
cout << count << endl;
}
return 0;
}
思路与上一问一样,逐日加。注意输出格式。有时候print比cout好用。
#include<iostream>
#include<stdio.h>
using namespace std;
int month[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} };
int isLeap(int y) {
return ((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0));
}
int main() {
int y, n;
int d, m;
while (scanf("%d %d",&y,&n)!=EOF) {
m = 1, d = 1;
while (--n) {
d++;
if (d == month[m][isLeap(y)]+1) {
m++;
d = 1;
}
}
printf("%04d-%02d-%02d\n", y, m, d);
}
return 0;
}
另外,也需要知道简单的二维数组的知识:c/c++简单的二维数组