求输入一个年份和月份,输出这个月的天数C语言程序设计
时间: 2024-10-18 21:18:11 浏览: 53
在C语言中,你可以使用`<time.h>`库来获取一个特定月份的天数。以下是一个简单的示例程序,它会接受用户输入的年份和月份,并输出该月的天数:
```c
#include <stdio.h>
#include <time.h>
int main() {
int year, month;
// 输入年份和月份
printf("请输入年份: ");
scanf("%d", &year);
printf("请输入月份(1-12): ");
scanf("%d", &month);
// 验证输入范围
if (month < 1 || month > 12) {
printf("错误:月份应介于1到12之间。\n");
return 1;
}
// 使用mktime函数计算指定月份的天数
struct tm date = {0};
date.tm_year = year - 1900; // mktime需要从公元1900年开始计数
date.tm_mon = month - 1; // 月份从0开始计数
time_t t = mktime(&date);
// 如果时间转换成功,获取并打印天数;失败则提示错误
if (t == (time_t)-1) {
perror("Error calculating days in the month");
} else {
int days_in_month = date.tm_mday;
printf("月份 %d 的天数是 %d\n", month, days_in_month);
}
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)