输入年份和月份,输出该月天数
时间: 2023-05-14 17:04:17 浏览: 100
这是一个常见的编程问题,可以使用以下代码来解决:
```python
import calendar
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
days = calendar.monthrange(year, month)[1]
print(f"{year}年{month}月有{days}天。")
```
这个程序使用了 Python 的 calendar 模块,其中的 monthrange 函数可以返回指定年份和月份的第一天是星期几以及该月的天数。我们只需要取出第二个返回值即可得到该月的天数。
相关问题
用switch语句编写:输入年份和月份输出该月天数
好的,以下是用 switch 语句编写的代码:
```c
#include <stdio.h>
int main() {
int year, month, days;
printf("请输入年份和月份,用空格隔开:");
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 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
printf("输入的月份不正确!");
return 0;
}
printf("%d 年 %d 月有 %d 天\n", year, month, days);
return 0;
}
```
希望这个代码能够帮到你!
输入年份和月份,输出该月的天数
以下是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(f"{year}年{month}月共有{days}天。")
```
代码逻辑如下:
1. 首先通过input函数获取用户输入的年份和月份,使用int函数将输入的字符串转换为整数类型。
2. 判断月份是否为2月,如果是则需要特殊处理。如果该年份为闰年,2月有29天;否则2月有28天。
3. 如果月份为4、6、9、11中的任意一个,该月有30天。
4. 如果月份既不是2月,也不是4、6、9、11中的任意一个,则该月有31天。
5. 将结果输出。