读入一个月份,输出该月有多少天(考虑闻年、平年情况),用switch语句编程。(闰年条件:能被4整除但不能被100整除,或y能被400整除的年份。)
时间: 2025-06-09 18:03:38 浏览: 34
在编程中,你可以使用switch语句结合日期相关的函数来处理这个问题。这里是一个简单的Python示例,它使用`calendar`模块来计算给定月份的天数:
```python
import calendar
def get_days_in_month(month, year):
days_in_month = {
"January": 31,
"February": 28,
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31,
}
if month in ("February", "April", "June", "September", "November"):
# 普通月份
days = days_in_month[month]
else:
# 一月、三月、五月、七月、八月、十月和十二月
days = days_in_month[month]
# 判断是否为闰年
is_leap_year = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if is_leap_year and month == "February":
days = 29 # 闰年的二月有29天
return days
# 使用 switch 语句的替代方案(虽然 Python 本身并不直接支持 switch )
def calculate_days(month, year):
months = {
'January': 31,
'February': lambda y: 29 if ((y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)) else 28,
'March': 31,
# ... 其他月份...
}
return months.get(month)(year)
# 测试
month = input("请输入月份(如 'January' 或 'February'):")
year = int(input("请输入年份:"))
days = calculate_days(month, year)
print(f"{month}有{days}天")
阅读全文
相关推荐


















