编写程序,提示用户输入月份和年份,然后显示这个月的天数。
时间: 2023-04-27 15:02:23 浏览: 138
以下是一个可以实现您要求的 Python 代码示例:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month == 2:
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
days = 29
else:
days = 28
elif month in [4, 6, 9, 11]:
days = 30
else:
days = 31
print("{}年{}月共有{}天。".format(year, month, days))
```
该代码首先提示用户输入年份和月份,然后根据年份和月份计算这个月的天数,并将结果输出。在计算天数时,程序考虑了闰年的情况。如果用户输入的月份不合法,例如输入了负数或大于 12 的数,程序将会出错。
相关问题
编写程序,提示用户输入年份和月份,然后显示这个月的天数。
您好,可以为您解答。请输入以下代码:
#include <stdio.h>
int main() {
int year, month, days;
printf("请输入年份和月份:\n");
scanf("%d%d", &year, &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 == && year % 100 != ) || year % 400 == )
days = 29;
else
days = 28;
break;
default:
printf("输入的月份有误!\n");
return ;
}
printf("%d年%d月有%d天。\n", year, month, days);
return ;
}
用python:编写程序提示用户输入月和年,然后显示这个月的天数。
可以使用 Python 自带的 calendar 模块来实现:
```python
import calendar
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 计算该月的天数
days_in_month = calendar.monthrange(year, month)[1]
print("{}年{}月共有 {} 天。".format(year, month, days_in_month))
```
输出结果类似于:
```
请输入年份:2021
请输入月份:2
2021年2月共有 28 天。
```