C---结构体---输入年、月、日,判断为输入年的第几天

定义一个结构体变量包括年月日,编写一个程序计算当天在本年中是第几天,注意闰年问题。

要计算一个特定日期在一年中的第几天,需要考虑闰年的情况。

闰年是:1、指能够被4整除的年份,2、不能被100整除而能被400整除的年份。

#include <stdio.h>

// 定义日期结构体
typedef struct {
    int year;
    int month;
    int day;
} Date;

// 函数声明
int isLeapYear(int year);
int dayOfYear(Date date);

int main() {
    Date today;

    // 获取用户输入的日期
    printf("请输入日期(年 月 日): ");
    scanf("%d %d %d", &today.year, &today.month, &today.day);

    // 计算并输出结果
    int dayNumber = dayOfYear(today);
    printf("%d年%d月%d日是该年的第%d天。\n", today.year, today.month, today.day, dayNumber);

    return 0;
}

// 判断是否为闰年的函数
int isLeapYear(int year) {
    return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}

// 计算日期在一年中的第几天的函数
int dayOfYear(Date date) {
    int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int dayCount = 0;

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

    // 累加从年初到当前月份的天数
    for (int i = 0; i < date.month - 1; i++) {
        dayCount += daysInMonth[i];
    }
    // 加上当前月份的天数
    dayCount += date.day;

    return dayCount;
}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值