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

相关推荐
vortex54 分钟前
探索 Shell:选择适合你的命令行利器 bash, zsh, fish, dash, sh...
linux·开发语言·bash·shell·dash
zzc9216 分钟前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
HUN金克斯15 分钟前
C++/C函数
c语言·开发语言·c++
慢半拍iii16 分钟前
数据结构——F/图
c语言·开发语言·数据结构·c++
钢铁男儿18 分钟前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
编程有点难21 分钟前
Python训练打卡Day43
开发语言·python·深度学习
m0_6371469326 分钟前
零基础入门 C 语言基础知识(含面试题):结构体、联合体、枚举、链表、环形队列、指针全解析!
c语言·开发语言·链表
GalaxyPokemon28 分钟前
LeetCode - 148. 排序链表
linux·算法·leetcode
LjQ204035 分钟前
网络爬虫一课一得
开发语言·数据库·python·网络爬虫