C语言 写一个函数days,实现某日在本年中是第几天计算。

写一个函数days,

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

由主函数将年、月、日传递给days函数,计算后将日子数传回主函数输出。

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;
}

[点击并拖拽以移动]
​

程序实现

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 days(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 = days(date);
    printf("The day is the %dth day of the year.\n", day);

    return 0;
}

代码解释:

  1. 定义 `days` 函数:编写 `days` 函数,实现第1题的计算逻辑。该函数接受年、月、日作为参数,并返回该日期在一年中的第几天。

  2. 主函数调用:在主函数中,读取用户输入的年、月、日,并调用 `days` 函数计算天数,最后将结果输出。

相关推荐
张张123y3 分钟前
后端第六课:Python 语法速通(0 基础入门,AI 应用开发的第一门语言)
开发语言·人工智能·python·ai·后端开发
Want5955 分钟前
Python跳动的爱心①
开发语言·python·数学建模
ydjs678899-bot44 分钟前
您的Next.js中间件匹配器配置可能会跳过您认为它保护的路由
开发语言·javascript·中间件
Chengbei111 小时前
JsOwl|AI 赋能 JS 敏感信息扫描器,AST + 正则、source‑map 源码还原、登录态爬虫输出交互式 HTML 报告
开发语言·javascript·网络·人工智能·爬虫·网络安全·自动化
David猪大卫1 小时前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
geovindu1 小时前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
Lxx_Zw1 小时前
先把轮子转稳,才不会烧心:编码器速度环 PID 怎么接回 PWM
c语言·stm32·单片机·嵌入式硬件
SDWAN_Cheap1 小时前
深度解析什么是CDN加速:从原理到实践的技术拆解
开发语言·cdn加速
鬼手点金1 小时前
模型即 Agent:当模型本身成为产品
开发语言·前端·人工智能·python·机器学习
头像很酷1 小时前
嵌入式虚拟化-xvisor-物理内存大管家
c语言·hypervisor·xvisor·嵌入式虚拟化