题解 | #计算日期到天数转换#

计算日期到天数转换

https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded

#include <iostream>
#include <vector>
using namespace std;

// 判断是否为闰年
bool isLeapYear(int year) {
    if (year % 400 == 0) return true;
    if (year % 100 == 0) return false;
    if (year % 4 == 0) return true;
    return false;
}

int dayOfYear(int year, int month, int day) {
    // 每个月的天数,非闰年
    vector<int> daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    // 如果是闰年,2月的天数改为29天
    if (isLeapYear(year)) {
        daysInMonth[1] = 29;
    }
    
    // 计算当年1月1日到当前日期的天数
    int dayOfYear = 0;
    for (int i = 0; i < month - 1; ++i) {
        dayOfYear += daysInMonth[i];
    }
    dayOfYear += day;
    
    return dayOfYear;
}

int main() {
    int year, month, day;
    cin >> year >> month >> day;

    // 计算并输出结果
    cout << dayOfYear(year, month, day) << endl;
    
    return 0;
}

全部评论

相关推荐

昨天 16:08
门头沟学院 运营
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
投递地平线等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务