用C语言写一段函数代码,输入年份,输出12个月每个月的天数
时间: 2024-12-12 09:17:34 浏览: 83
当然,你可以使用C语言编写一个函数来计算给定年份每个月的天数。这里我们假设输入的是公历年份(非闰年),因为公历闰年的规则比较复杂,包括能被4整除但不能被100整除,或者能被400整除的情况。以下是一个简单的实现,不考虑闰年:
```c
#include <stdio.h>
int month_days(int year, int month) {
// 对于每月的天数定义
static const int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
// 如果是闰年,二月有29天
days_in_month[2] = 29;
} else {
// 非闰年,二月有28天
}
return days_in_month[month];
}
int main() {
int year, month;
printf("Enter the year and the month (1-12): ");
scanf("%d %d", &year, &month);
if (month >= 1 && month <= 12) {
int days = month_days(year, month);
printf("The number of days in %d-%02d is %d\n", year, month, days);
} else {
printf("Invalid month entered.\n");
}
return 0;
}
```
在这个代码中,`month_days` 函数接收年份和月份作为参数,返回对应月份的天数。主函数中用户输入年月后调用这个函数并打印结果。
注意,这个程序没有处理用户输入验证(如是否为合法的年份和月份),在实际应用中你可能希望增加这样的错误检查。此外,为了简化,没有考虑到世纪闰年(例如公元2000年是闰年)的特殊情况,如果你要实现更精确的日期处理,你需要加入这部分逻辑。
阅读全文
相关推荐


















