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` 函数计算天数,最后将结果输出。

相关推荐
悟能不能悟15 分钟前
JAVA 对象转为二级制流,再转化为base64
java·开发语言
进击的前栈1 小时前
Flutter跨平台网络图片缓存库cached_network_image鸿蒙化适配指导手册
开发语言·网络·rust
老华带你飞1 小时前
房屋租赁管理系统|基于java+ vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Alex Cafu1 小时前
Linux网络编程1(OSI模型与TCP/IP协议栈)
linux·c语言·网络·tcp/ip
AC赳赳老秦1 小时前
行业数据 benchmark 对比:DeepSeek上传数据生成竞品差距分析报告
开发语言·网络·人工智能·python·matplotlib·涛思数据·deepseek
TheITSea1 小时前
Java中的Optional:从入门到精通
java·开发语言
博语小屋1 小时前
转义字符.
c语言·c++
糕......1 小时前
Java异常处理完全指南:从概念到自定义异常
java·开发语言·网络·学习
御水流红叶1 小时前
第七届金盾杯(第一次比赛)wp
开发语言·python
Lhan.zzZ1 小时前
Qt跨线程网络通信:QSocketNotifier警告及解决
开发语言·c++·qt