c语言输入一个年份和月份,输出这个月的天数
时间: 2024-11-09 15:26:38 浏览: 20
输出每个月的天数C语言PTA
在C语言中,你可以通过库函数`mktime()`和`strftime()`来实现这个功能。首先,你需要判断给定的年份是否是闰年,因为某些月份的天数会因是否为闰年而变化。然后,根据输入的月份计算对应的天数。
下面是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int days_in_month(int year, int month) {
static const struct tm months[] = {
{0, 1, 31}, {0, 3, 31}, {0, 4, 30}, {0, 6, 30},
{0, 9, 30}, {0, 11, 30}, {0, 12, 31}
};
// 判断是否为闰年
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
months[1].tm_mday++; // February has 29 days in a leap year
}
// 使用mktime()将输入转化为struct tm结构,然后获取天数
time_t t = mktime(&(struct tm){
.tm_year = year - 1900,
.tm_mon = month - 1, // months start from 0
.tm_mday = 1, // initialize with first day
.tm_hour = 0, // time part not needed
.tm_min = 0,
.tm_sec = 0,
.tm_wday = 0,
.tm_yday = 0,
.tm_isdst = -1 // assume local timezone
});
if (t == (time_t)-1) {
printf("Invalid date.\n");
return 0;
}
return days_in_month = mktime(&months[month - 1]);
}
int main() {
int year, month;
printf("Enter the year and month (YYYY MM): ");
scanf("%d %d", &year, &month);
// 确保输入的是1到12之间的月份
if (month < 1 || month > 12) {
printf("Invalid month number.\n");
return 1;
}
int days = days_in_month(year, month);
if (days > 0)
printf("Number of days in %d-%02d is %d.\n", year, month, days);
return 0;
}
```
阅读全文