获取用户输入月份,输出该月有多少天(考虑闰年)
时间: 2023-10-26 08:17:56 浏览: 34
好的,这是一个关于日期计算的问题,我可以为您提供一个 Python 的代码示例:
```python
year = int(input("请输入年份: "))
month = int(input("请输入月份: "))
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
days = 29
else:
days = 28
print(f"{year}年{month}月有{days}天")
```
您可以将上述代码保存为一个 .py 文件,然后在命令行中运行该文件,按照提示输入年份和月份,即可输出该月有多少天。需要注意的是,这个计算方法是按照公历来计算的,如果您需要使用其他日历来计算日期,可能需要进行特殊处理。
相关问题
获取用户输入月份,输出该月有多少天(考虑闰年
)。
提示:
闰年的判断方法为:能被4整除但不能被100整除,或者能被400整除的年份为闰年。
以下是Python代码实现:
```python
month = int(input("请输入月份:"))
year = int(input("请输入年份:"))
if month in [1, 3, 5, 7, 8, 10, 12]:
print("{0}年{1}月有31天".format(year, month))
elif month in [4, 6, 9, 11]:
print("{0}年{1}月有30天".format(year, month))
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("{0}年{1}月有29天".format(year, month))
else:
print("{0}年{1}月有28天".format(year, month))
else:
print("输入月份有误!")
```
获取用户输入月份,输出该月有多少天(考虑闰年)
```python
month = int(input("请输入月份:"))
if month in [1, 3, 5, 7, 8, 10, 12]:
print("{}月有31天".format(month))
elif month in [4, 6, 9, 11]:
print("{}月有30天".format(month))
elif month == 2:
year = int(input("请输入年份:"))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("{}年{}月有29天".format(year, month))
else:
print("{}年{}月有28天".format(year, month))
else:
print("输入月份有误")
```
说明:
1. 首先,通过 `input()` 函数获取用户输入的月份,将其转换成整数。
2. 接着,使用 `if-elif-else` 语句判断该月份有多少天。其中,1、3、5、7、8、10、12月有31天,4、6、9、11月有30天,2月需要根据闰年进行判断。
3. 对于判断闰年的条件,可以使用以下规则:
- 能被4整除但不能被100整除的年份是闰年;
- 能被400整除的年份也是闰年。
4. 最后,根据判断结果输出该月份有多少天。如果输入的月份不在1-12之间,则输出提示信息。