您的位置:首页 > 其它

九度OJ1096 日期差值

2013-06-10 20:26 204 查看
题目链接:http://ac.jobdu.com/problem.php?pid=1096

题目分析:

这题是交大的一年的机试题,不难,不过需要考虑的比较详细。

我设计的程序的思想是,首先判断两年是否在同一年,然后再判断两年是否在同一月,然后进行日期差值的计算。这里要注意天数的差值的加1问题。同时还要在每一种情况下考虑闰年二月天数的问题。我使用数组存储每个月的天数,然后在计算的时候首先判断是否是闰年,再重新赋值给二月的天数。

要注意一些细节的问题,考虑要周到,就可以了。

源代码:

#include<iostream>
#include<cmath>
#include <cstdlib>
using namespace std;

int main()
{
int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};    //月份数组
int s1 = 0,s2 = 0;
while (cin>>s1>>s2)
{
int n = 0;    //相隔天数
int a,b,c,d,e,f;
int y = 0;    //标记相隔年数
int m = 0;    //标记相隔月数
a = s1 / 10000;    //第一个年份
b = s2 / 10000;    //第二个年份
c = (s1 % 10000) / 100;        //第一个月份
d = (s2 % 10000) / 100;        //第二个月份
e = (s1 % 10000) % 100;        //第一个天数
f = (s2 % 10000) % 100;        //第二个天数
y = abs(b - a);

if (y == 0)    //两年在同一年
{
m = abs(d - c);
if (m == 0)    //两月在同一月
{
n = abs(f - e) + 1;
}
else    //两月不在同一月
{
if (b % 4 == 0  && b % 100 != 0 || b % 400 == 0)    //当前年是闰年
{
month[1] = 29;
for (int i = c; i < d; i++)
{
n = n + month[i - 1];
}
n = n - e + 1 + f;    //计算间隔天数
}
else    //当前年不是闰年
{
month[1] = 28;
for (int i = c; i < d; i++)
{
n = n + month[i - 1];
}
n = n - e + 1 + f;
}
}
}
else    //两年不在同一年
{
int j = 0;    //闰年个数
for(int i = a + 1; i < b; i ++)
{
if (i % 4 == 0  && i % 100 != 0 || i % 400 == 0)    //判断闰年
{
j ++;
}
}
n = abs(b - a - 1) * 365 + j;    //相隔年数转化为天数

if (a % 4 == 0  && a % 100 != 0 || a % 400 == 0)    //起始年为闰年
{
month[1] = 29;
for(int i = c; i <= 12; i ++)
{
n = n + month[i - 1];
}
n = n - e + 1;
}
else    //起始年不是闰年
{
month[1] = 28;
for(int i = c; i <= 12; i ++)
{
n = n + month[i - 1];
}
n = n - e + 1;
}
if (b % 4 == 0  && b % 100 != 0 || b % 400 == 0)    //结束年为闰年
{
month[1] = 29;
for(int i = 1; i < d; i ++)
{
n = n + month[i - 1];
}
n = n + f;
}
else    //结束年不是闰年
{
month[1] = 28;
for(int i = 1; i < d; i ++)
{
n = n + month[i - 1];
}
n = n + f;
}
}
cout<<n<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: