编写程序实现,根据输入年份和月份,输出该月有多少天。(15分) 例如:输入 201902 输出 28 提示:闰年判断条件是年份能被400整除或被4整除而不能被100整除。
时间: 2023-05-10 19:55:53 浏览: 52
以下是实现该功能的 Python 代码:
```python
def days_in_month(year, month):
if month == 2:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return 29
else:
return 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
days = days_in_month(year, month)
print("{}年{}月有{}天".format(year, month, days))
```
例如,输入 201902,输出结果为:
```
2019年2月有28天
```
注意,这里使用了 if-elif-else 语句来判断每个月的天数,其中 2 月需要特殊处理,其他月份可以根据奇偶性来判断。
相关问题
编写一个程序,提示用户输入月份和年份,输出该月的天数。要求:编程语言使用C++.
以下是C++代码:
```c++
#include <iostream>
using namespace std;
int main()
{
int month, year;
cout << "请输入月份和年份(如:3 2022):" << endl;
cin >> month >> year;
int days;
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:
cout << "输入的月份有误!" << endl;
return 0;
}
cout << year << "年" << month << "月有" << days << "天。" << endl;
return 0;
}
```
程序的流程如下:
1. 提示用户输入月份和年份;
2. 读入用户输入的月份和年份;
3. 通过 switch 语句计算该月的天数,并将结果存储在变量 days 中;
4. 输出结果。
其中,通过 switch 语句计算该月的天数的逻辑如下:
1. 对于 1、3、5、7、8、10、12 月,天数为 31 天;
2. 对于 4、6、9、11 月,天数为 30 天;
3. 对于 2 月,如果该年是闰年,天数为 29 天;否则天数为 28 天。
注意,程序还添加了一些错误处理的逻辑,例如对于无效输入的月份,程序会输出错误提示信息并退出。
编写程序从键盘输入年份值和月份值输出该年当月的日历
以下是Python程序,可以实现从键盘输入年份值和月份值,输出该年当月的日历。
```python
import calendar
year = int(input("请输入年份值:"))
month = int(input("请输入月份值:"))
# 输出日历
print(calendar.month(year, month))
```
运行程序后,会先提示用户输入年份值和月份值,然后调用 `calendar.month()` 函数输出对应年月的日历。
例如,输入年份值为2021,月份值为6,程序将输出2021年6月的日历:
```
请输入年份值:2021
请输入月份值:6
June 2021
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
```