第几天?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 207719 Accepted Submission(s): 72592
Problem Description
给定一个日期,输出这个日期是该年的第几天。
Input
输入数据有多组,每组占一行,数据格式为YYYY/MM/DD组成,具体参见sample input ,另外,可以向你确保所有的输入数据是合法的。
Output
对于每组输入数据,输出一行,表示该日期是该年的第几天。
Sample Input
1985/1/20
2006/3/12
Sample Output
20
71
问题链接:[https://vjudge.net/problem/HDU-2005]
问题分析:
1)要知道该日期在该年的哪一天,首先要考虑该年是否为闰年(①非整百年能被4整除的为闰年。②能被400整除的是闰年。)用if。。。else。。。语句实现判别。
2)闰年与平年的二月的天数不同,利用两个数组将不同年份的月份天数存储,再利用循环进行月份的加减(不然就得考虑十二种情况了,外加闰年的二月,十三种,复杂。。。)。
3)将输入当成循环条件实现多组循环。
已AC过的代码
一个比较复杂(利用了结构体):
#include<iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
void days(Date &, int &);
int main()
{
Date today;
int n = 0;
char c,a;
while (cin >> today.year >>c>> today.month >>a>> today.day)
{
days(today, n);
cout << n << endl;
}
}
void days(Date &today, int &n)
{
n = 0;
int r[] = { 31,29,31,30,31,30,31,31,30,31,30,31 };
int ur[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if ((today.year % 4 == 0 && today.year % 100 != 0) || (today.year % 400 == 0))
{
int i;
for (i = 0;i < today.month;i++)
{
n += r[i];
}
n = n - r[i - 1] + today.day;
}
else
{
int i;
for (i = 0;i < today.month;i++)
{
n += ur[i];
}
n = n - ur[i - 1] + today.day;
}
}
另一个AC过的(其实一样的):
#include<iostream>
using namespace std;
int main()
{
int i, year, month,day,n;
char a, b;
int r[12] = { 31,29,31,30,31,30,31,31,30,31,30,31 };
int ur[12] = { 31,28,31,30,31,30,31,30,31,31,30,31 };
while (cin >> year>>a >> month>>b>> day)
{
n = 0;
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{
for ( i = 0;i < month-1;i++)
n += r[i];
n = n + day;
}
else
{
for ( i = 0;i < month-1;i++)
n += ur[i];
n = n +day;
}
cout << n<<endl;
}
}