【牛客】[编程题]计算日期到天数转换C++

1.题目描述

链接:https://www.nowcoder.com/questionTerminal/769d45d455fe40b385ba32f97e7bcded?toCommentId=204001

根据输入的日期,计算是这一年的第几天。。

详细描述:

输入某年某月某日,判断这一天是这一年的第几天?。

2.思路分析

  1. 先定义一个数组,这个数组就是十二个月份,二月给成28
  2. 写一个闰年函数,是闰年的话,那就给二月+1
  3. 然后循环+=,退出条件就是月份
  4. 最后一个月份一定要加上day
  5. 最后打印

3.代码实现

#include <iostream>
using namespace std;

// 判断是不是闰年
bool boolyear(int _year)
{
    if(_year % 400 == 0|| (_year % 4 == 0 && _year % 100 != 0))
        return true;
    return false;
}

int main()
{
    int year, month, day;
    // 十二个月的天数,只有二月要判断是否闰年+1
    int arr[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    // 算出所有的月的和
    int sum = 0;
    while(cin >> year >> month >> day)
    {
        // 因为多组数据,所以每次置为0
        sum = 0;
        // 如果是闰年,下面肯定arr[1]肯定会是29,所以要在这里把他置为28
        // 在判断是不是闰年,是否要在+1
        arr[1] = 28;
        if(boolyear(year))
            arr[1] = 29;
        // 将前month - 1个月的天数加起来
        for(int i = 0; i < month - 1; i++)
            sum += arr[i];
        // 加最后一个月
        sum += day;
        // 打印
        cout << sum << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43967449/article/details/106786804