【算法笔记】DAY2_3.3图形输出&3.4日期差值

3.3  图形输出

[PAT B1036] 和奥巴马一起编程

3.4 日期处理

[codeup 1928]1928: 日期差值

关于平年和闰年的知识

平年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;
}

[codeup] 问题 C: 打印日期

思路与上一问一样,逐日加。注意输出格式。有时候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++简单的二维数组

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值