算法题:计算一年中的第几天

题目:给出年月日的日期,算出该天是这年的第几天

需要考虑闰年的情况,也需要考虑大月、小月、以及二月;

题目不难,只需考虑周全即可

代码如下:

@author xionglei
 
@date 2018/03/04
 
#include<iostream>
using namespace std;
int solution(int year,int month,int day) 
{ 
    int leap=0;
    int big=0; 
    int result=0;
    if((year%4==0&&year%100!=0) || year%400==0)           //算出闰年
        leap=1;
    if(month<=8)
        for(int i=1;i<month;i+=2)  ++big;         //算出大月
    else{
        big=4;
        for(int i=8;i<month;i+=2) ++big;
    }     
    if(month<=2)
        result=30*(month-1)+big+day; 
    else 
        result=30*(month-1)+big+day-2+leap; 
    return result; 
}
 
int main() 
{
    int year,month,day;
    while(cin>>year>>month>>day)
    {
        int result=solution(year,month,day);
        cout<<result;
    }
    return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_38506897/article/details/79450852