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

相关推荐
lueluelue4719 小时前
LeetCode:链表
算法·leetcode·链表
隐积20 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
huameinan狮子1 天前
Adaboost算法原理与计算实例
算法
别怪我很水1 天前
API中提供了VelocityTracker类用于计算触摸事件MotionEvent的速度,而其内部默认使用的方法就是最小二乘法,本 ...
算法·gitee·最小二乘法
名字还没想好☜1 天前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
初级代码游戏1 天前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
酷在前行1 天前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr8281 天前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱