XTU 1103 日期

Description
给出一个日期,请计算这天是这一年的第几天? 输入 第一行是一个整数N,表示样例的个数,以后每行一个日期,日期格式满足“YYYY-MM-DD”的格式(即年4位,月2位,日期2位)。 输出 每行输出一个整数,即第几天,输入保证日期的合法性。

Sample Input
3
2000-02-29
2001-02-01
2001-02-28

Sample Output
60
32
59

开数组存入每个月份的天数(二月先存为28天),判断为闰年则二月份天数加一。由于输入日期格式为string,用atoi()函数把年月日分别转为了int。不知道还有没有好的方法。

# include<iostream>
# include<vector>
# include<string>
# include<stdlib.h>
using namespace std;

bool is_leap_yaer(int y)
{
    return ((y%4==0&&y%100!=0)||y%400==0)?true:false;
}

int main()
{
    int num_day[13]={31,28,31,30,31,30,31,31,30,31,30,31};
    int n;
    cin>>n;
    cin.get();
    while(n--)
    {
        string date;
        cin>>date;
        int year,month,day;
        char year2[5],month2[4],day2[3];
        for(int i=0,j=0;i<4;i++,j++)
            year2[j]=date[i];
        for(int i=5,j=0;i<7;i++,j++)
            month2[j]=date[i];
        for(int i=8,j=0;i<10;i++,j++)
            day2[j]=date[i];
        year=atoi(year2);
        month=atoi(month2);
        day=atoi(day2);
        int ans=0;
        if(is_leap_yaer(year))
            num_day[1]=29;
        for(int i=0;i<month-1;i++)
            ans+=num_day[i];
        ans+=day;
        cout<<ans<<endl;
        ans=0;
        num_day[1]=28;
    }
}

猜你喜欢

转载自blog.csdn.net/oslowwalker/article/details/83089559