题目1096:日期差值(a-b=(a-c)-(b-c))
http://ac.jobdu.com/problem.php?pid=1096
题目描述:
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
输入:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出:
每组数据输出一行,即日期差值
样例输入:
20110412
20110422
样例输出:
11
思路:
计算2011 00 00到2011 04 12的天数为acount;计算2011 00 00到2011 04 22的天数为bcount;最终结果应该是acount-bcount+1。
代码:
# include<iostream> using namespace std; int main() { int m[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; char a[8], b[8]; int ya, yb, ma, mb, da, db; int i, j, k, acount, bcount; while (cin >> a >> b) { ya = (a[0] + (0 - '0')) * 1000 + (a[1] + (0 - '0')) * 100 + (a[2] + (0 - '0')) * 10 + (a[3] + (0 - '0')); yb = (b[0] + (0 - '0')) * 1000 + (b[1] + (0 - '0')) * 100 + (b[2] + (0 - '0')) * 10 + (b[3] + (0 - '0')); ma = (a[4] + (0 - '0')) * 10 + (a[5] + (0 - '0')); mb = (b[4] + (0 - '0')) * 10 + (b[5] + (0 - '0')); da = (a[6] + (0 - '0')) * 10 + (a[7] + (0 - '0')); db = (b[6] + (0 - '0')) * 10 + (b[7] + (0 - '0')); //cout << ya << " " << ma << " " << da << endl; //cout << yb << " " << mb << " " << db << endl; acount = 0; for (i = 1; i < ma; i++) { acount += m[i]; } if (ma>2 && ((ya % 4 == 0 && ya % 100 != 0) || ya % 400 == 0)) { acount += 1; } acount += da; bcount = 0; for (i = ya; i < yb; i++)//not <= { if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) { bcount += 366; } else { bcount += 365; } } for (i = 1; i < mb; i++) { bcount += m[i]; } if (mb>2 && ((yb % 4 == 0 && yb % 100 != 0) || yb % 400 == 0)) { bcount += 1; } bcount += db; cout << bcount - acount + 1 << endl; } return 0; } /************************************************************** Problem: 1096 User: mmcNuaa@163.com Language: C++ Result: Accepted Time:0 ms Memory:1520 kb ****************************************************************/