根据提示,在右侧编辑器补充代码实现:从键盘输入某年某月(包括闰年),用switch语句编程输出该年的该月拥有的天数。要求考虑闰年及输入月份不在合法范围内的情况。已知闰年的2月有29天,平年的2月有28天。
时间: 2024-10-01 11:06:37 浏览: 76
下面是一个Python代码示例,实现了你所描述的功能:
```python
def get_days_in_month():
year = int(input("请输入年份:"))
month = int(input("请输入月份(范围1-12):"))
# 判断输入是否合法
if not 1 <= month <= 12:
print("月份输入错误,请输入1到12之间的整数。")
return
# 判断闰年和平年
is_leap_year = False
if year % 4 == 0:
if year % 100 != 0 or (year % 100 == 0 and year % 400 == 0):
is_leap_year = True
# 使用switch语句模拟
days_in_month = {
1: 31,
2: is_leap_year * 29 + (not is_leap_year) * 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
print(f"{year}年{month}月共有 {days_in_month[month]} 天")
get_days_in_month()
```
在这个函数中,首先获取用户输入的年份和月份,然后判断月份是否在1到12之间。接着通过if-else结构确定是否为闰年。最后,使用字典`days_in_month`存储每个月的天数,根据输入的月份返回对应的天数。
注意,虽然Python语言本身并不支持直接的`switch`语句,但这里通过字典的方式实现了类似的效果。
阅读全文
相关推荐















