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

相关推荐
鲸渔12 小时前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
星恒随风13 小时前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
风落青芜13 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z13 小时前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah13 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai454513 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
Zwawa14 小时前
步进电机路径规划:梯形曲线与S型曲线
c语言·单片机·嵌入式
草履虫AI课14 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
AAA修煤气灶刘哥15 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
ShineWinsu15 小时前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤