计算日期到天数转换(HJ73)

一:解题思路

这道题题目关键要弄清楚闰年和非闰年的的区别,闰年2月份有29天,非闰年2月份有28天。判断闰年的充分必要条件是,年份能够被4整除,但不能够100整除,或者年份能够被100整数,也能够被400整除。

二:完整代码示例 (C++版和Java版)

C++代码:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int year = 0;
    int month = 0;
    int day = 0;
    vector<int> months = {0,31,28,31,30,31,30,31,31,30,31,30,31};

    while (cin >> year >> month >> day)
    {
        int dateCount = day;

        if (year % 4 == 0 && year % 100 != 0)
        {
            months[2] = 29;
        }
        else if (year % 100 == 0 && year % 400 == 0)
        {
            months[2] = 29;
        }
        else
            months[2] = 28;
        
        for (int i = 1; i < month; i++)
        {
            dateCount += months[i];
        }

        cout << dateCount << endl;
    }

    return 0;
}
posted @ 2020-07-31 22:14  repinkply  阅读(521)  评论(0)    收藏  举报