C语言 计算给定日期是当年的第几天

.给出年、月、日,计算该日是该年的第几天。

#include <stdio.h>

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

// 计算日期是当年的第几天
int day_of_year(int year, int month, int day) {
    int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (is_leap_year(year)) {
        days_in_month[1] = 29;
    }
    int day_of_year = 0;
    for (int i = 0; i < month - 1; i++) {
        day_of_year += days_in_month[i];
    }
    day_of_year += day;
    return day_of_year;
}

int main() {
    int year, month, day;
    printf("输入年、月、日:");
    scanf("%d %d %d", &year, &month, &day);
    
    int result = day_of_year(year, month, day);
    
    printf("这一天是这一年的第%d天\n", result);
    
    return 0;
}

解释说明:

计算天数:

  • 函数 is_leap_year 判断年份是否为闰年。
  • 函数 day_of_year 根据输入的年月日计算该日期是当年的第几天。
  • 主函数从键盘输入年、月、日,调用 day_of_year 函数并输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值