C语言 定义结构体变量并计算该日在本年中是第几天

定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年问题(即将闰年情况包含在内)。

#include <stdio.h>

typedef struct {
    int year;
    int month;
    int day;
} Date;

int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        return 1;
    return 0;
}

int daysOfMonth(int month, int year) {
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year))
        return 29;
    return days[month - 1];
}

int dayOfYear(Date date) {
    int days = 0;
    for (int i = 1; i < date.month; i++) {
        days += daysOfMonth(i, date.year);
    }
    days += date.day;
    return days;
}

int main() {
    Date date;
    printf("Enter year, month, day: ");
    scanf("%d %d %d", &date.year, &date.month, &date.day);

    int day = dayOfYear(date);
    printf("The day is the %dth day of the year.\n", day);

    return 0;
}

代码解释:

1. 定义结构体:定义一个名为 `Date` 的结构体,其中包括年、月、日三个成员变量。

2. 判断闰年:编写一个函数 `isLeapYear`,用于判断给定年份是否为闰年。闰年的判断依据是:年份能被4整除但不能被100整除,或者能被400整除。

3. 计算天数:编写一个函数 `dayOfYear`,该函数接受一个 `Date` 类型的变量作为参数,返回该日期在该年中的第几天。函数首先确定每个月的天数(考虑到闰年二月的不同天数),然后累加至给定日期,计算出天数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值