c语言实现输入年月,对应的输出对应月份的天数
时间: 2024-10-10 15:15:32 浏览: 99
在 C 语言中,你可以通过创建一个函数来实现这个功能。首先,你需要一个包含月份天数的数组或者一个 switch-case 结构来存储每个月的天数。以下是一个简单的示例:
```c
#include <stdio.h>
int getDaysInMonth(int month, int year) {
// 创建一个数组保存每个月的天数(假设是公历)
static const int daysInMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 考虑闰年的规则
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { // 非世纪年或世纪闰年
if (month == 2) {
return 29;
}
} else {
// 平年
if (month == 2) {
return 28;
}
}
// 根据输入的月份返回相应天数
return daysInMonths[month - 1]; // 减一是因为数组索引从0开始
}
int main() {
int month, year;
printf("请输入年份和月份(例如:2023 02): ");
scanf("%d %d", &year, &month);
int days;
if (getDaysInMonth(month, year) > 0) {
days = getDaysInMonth(month, year);
printf("年份 %d 月份 %d 的天数是 %d\n", year, month, days);
} else {
printf("输入错误,月份 %d 不存在或非闰年的二月只有28天。\n", month);
}
return 0;
}
```
当你运行这个程序并输入年月时,它会计算出该年的指定月份有多少天,并打印出来。如果用户输入的是非标准的月份或闰年二月,程序会给出相应的提示。
阅读全文
相关推荐


















