c语言 终端输入一个日期,判断是这一年的第几天

#include <stdio.h>

// 判断是否是闰年
int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        return 1; // 是闰年
    } else {
        return 0; // 不是闰年
    }
}

// 计算日期是该年的第几天
int dayOfYear(int year, int month, int day) {
    // 每个月的天数,平年
    int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    // 如果是闰年,2月天数为29天
    if (isLeapYear(year)) {
        daysInMonth[1] = 29;
    }

    // 检查日期的合法性
    if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]) {
        printf("输入的日期无效。\n");
        return -1;
    }

    // 计算天数总和
    int dayOfYear = day;
    switch (month - 1) {
        case 11: dayOfYear += 30; // 12月
        case 10: dayOfYear += 31; // 11月
        case 9: dayOfYear += 30; // 10月
        case 8: dayOfYear += 31; // 9月
        case 7: dayOfYear += 31; // 8月
        case 6: dayOfYear += 30; // 7月
        case 5: dayOfYear += 31; // 6月
        case 4: dayOfYear += 30; // 5月
        case 3: dayOfYear += 31; // 4月
        case 2: dayOfYear += 28; // 3月,平年2月28天
                if (isLeapYear(year)) dayOfYear++; // 闰年2月29天
        case 1: dayOfYear += 31; // 2月
    }

    return dayOfYear;
}

int main() {
    int year, month, day;
    printf("请输入一个日期(格式:YYYY-MM-DD):");
    scanf("%d-%d-%d", &year, &month, &day);

    int dayOfYearResult = dayOfYear(year, month, day);
    if (dayOfYearResult != -1) {
        printf("输入的日期是这一年的第 %d 天\n", dayOfYearResult);
    }

    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值