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

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

cpp 复制代码
#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` 类型的变量作为参数,返回该日期在该年中的第几天。函数首先确定每个月的天数(考虑到闰年二月的不同天数),然后累加至给定日期,计算出天数。

相关推荐
90后小陈老师17 分钟前
用户管理系统 05 实现后端注册功能 | Java新手实战 | 最小架构 | 期末实训 | Java+SpringBoot+Vue3
java·开发语言·spring boot·后端·spring·maven·mybatis
闲人编程33 分钟前
Python对象模型:一切都是对象的设计哲学
开发语言·python·模型·对象·codecapsule·下划线
列逍36 分钟前
深入理解 C++ 智能指针:原理、使用与避坑指南
开发语言·c++
二川bro38 分钟前
Python大语言模型调优:LLM微调完整实践指南
开发语言·python·语言模型
4***V20243 分钟前
PHP在微服务通信中的消息队列
开发语言·微服务·php
亿坊电商1 小时前
PHP框架 vs 原生开发:移动应用后端开发实战对比!
开发语言·php
dvvvvvw1 小时前
*菱形.c
c语言
S***q1921 小时前
Kotlin内联函数优化
android·开发语言·kotlin
在路上看风景1 小时前
2.3 C#装箱和拆箱
开发语言·c#
坚持就完事了1 小时前
蓝桥杯中Python常用的库与模块
python·算法