给定一个日期,输出这个日期是该年的第几天。
1985/1/20 2006/3/12
20 71
这个题,我没有用数组,而是用纯数学方法解答,比较麻烦复杂。
#include <stdio.h>
int main ()
{
int y,m,d,s;
while (scanf("%d/%d/%d",&y,&m,&d)!=EOF)
{
if(m<=2)
{
s=(m-1)*31+d;
}
else
{
if(m>2&&m<=7)
{
s=(m-1)*31-(m-1)/2+d;
}
else
{
s=(m-1)*31-(m-2)/2+d;
}
if((y%4==0&&y%100!=0)||y%400==0)
{
s=s-1;
}
else{s=s-2;
}
}
printf("%d\n",s);
}
return 0;
}
数组解法:
#include <stdio.h>
int main ()
{
int y,m,d;
while (scanf("%d/%d/%d",&y,&m,&d)!=EOF)
{
int sum=0;
int s[12]={31,28,31,30,31,30,31,31,30,31,30};
for(int j=0;j<m-1;j++)
{
sum+=s[j];
}
if(((y%4==0&&y%100!=0)||y%400==0)&&m>2)printf("%d\n",sum=sum+d+1);
else printf("%d\n",sum=sum+d);
}
return 0;
}
switch解法:
# include <stdio.h>
int main ()
{
int y,m,d;
while (scanf("%d/%d/%d",&y,&m,&d)!=EOF)
{
int sum=0;
switch(m)
{
case (12):sum+=30;
case (11):sum+=31;
case (10):sum+=30;
case (9):sum+=31;
case (8):sum+=31;
case (7):sum+=30;
case (6):sum+=31;
case (5):sum+=30;
case (4):sum+=31;
case (3):if((y%4==0&&y%100!=0)||y%400==0)sum+=29; else sum+=28;
case (2):sum+=31;
case (1):sum+=d;
}
printf("%d\n",sum);
}
return 0;
}