输入年份和天数计算出几月几号

本文介绍了一个用于将指定年份中的第几天转换为具体月份和日期的C语言函数。该函数通过传入年份和年中第几天,并通过指针返回对应的月份和日期。此外,还考虑了闰年的情况。

//转换函数如下,其中通过指针同时向主函数传回月份和天数

void month_day(int year, int yearday, int *month, int *day){

//k月份,leap判断是否闰年(0非闰年1闰年)
int k, leap;
int tab[2][13] = {
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
};
leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
for (k = 1; yearday>tab[leap][k]; k++){
yearday = yearday - tab[leap][k];
}
*day = yearday;
*month = k;
}
在 C 语言中,你可以通过指针数组来实现这样的功能。首先,你需要两个变量,一个存储年份(整型 int),另一个存储总天数(也应该是整型)。假设用户输入的是从年初到现在的天数,你需要考虑每个月的天数差异,包括闰年的处理。 下面是一个简单的示例程序: ```c #include <stdio.h> int main() { int year, total_days; printf("请输入年份: "); scanf("%d", &year); printf("请输入天数: "); scanf("%d", &total_days); // 定义月份天数数组,注意二月需要特殊处理闰年的情况 int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int current_month = 1; // 当前月份,默认为1月 for (int i = 0; i < total_days; ++i) { if (current_month == 2 && is_leap_year(year)) { days_in_month[2] = 29; // 闰年二月有29天 } if (days_in_month[current_month - 1] <= i) { i -= days_in_month[current_month - 1]; current_month++; } else { break; } } printf("第%d个月第%d天\n", current_month, i + 1); // 加1是因为我们是从0开始计数的 return 0; } // 辅助函数判断是否为闰年 bool is_leap_year(int year) { if (year % 4 != 0) return false; else if (year % 100 != 0) return true; else if (year % 400 != 0) return false; else return true; } ``` 在这个程序中,我们遍历每一天,直到达到指定的总天数,然后记录当前月份。注意闰年的处理是在`is_leap_year`辅助函数中完成的。这个实现假设用户只输入了一个自然年内的天数,并且忽略了一年中的其他特殊情况,比如连续闰年等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值