根据输入的年份和月份判断该月的天数
时间: 2023-12-19 09:06:42 浏览: 107
以下是Python的代码实现:
```
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month == 2:
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("该月有29天")
else:
print("该月有28天")
elif month in (4, 6, 9, 11):
print("该月有30天")
else:
print("该月有31天")
```
首先通过`input`函数获取用户输入的年份和月份,然后根据月份的不同进行判断。如果是2月,需要进一步判断该年份是否为闰年,如果是,则该月有29天,否则有28天。对于4、6、9、11月,都是30天,其他月份都是31天。
相关问题
python根据输入的年份和月份判断该月的天数
可以使用calendar模块来判断一个月的天数。下面是一个示例代码:
```python
import calendar
def get_days_in_month(year, month):
# 判断该月的天数
days = calendar.monthrange(year, month)[1]
return days
year = int(input("请输入年份: "))
month = int(input("请输入月份: "))
days_in_month = get_days_in_month(year, month)
print(f"{year}年{month}月有{days_in_month}天。")
```
c语言根据输入月份和年份求该月天数
以下是一个示例程序,可以根据输入的月份和年份计算该月的天数:
```c
#include <stdio.h>
int main()
{
int year, month, days;
printf("请输入年份:");
scanf("%d", &year);
printf("请输入月份:");
scanf("%d", &month);
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
printf("输入的月份有误!\n");
return 1;
}
printf("%d年%d月有%d天。\n", year, month, days);
return 0;
}
```
程序中使用了一个 switch 语句来根据月份计算天数。其中,1、3、5、7、8、10、12 月都有 31 天,4、6、9、11 月都有 30 天,2 月根据年份是否为闰年来确定天数。如果是闰年,则有 29 天;否则只有 28 天。注意,闰年的判断方法是:能被 4 整除但不能被 100 整除,或者能被 400 整除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.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)
![](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)