编写一个程序,输入年和月,输出该月有多少天
时间: 2024-05-15 16:18:19 浏览: 26
好的,可以使用 Python 编写一个简单的程序实现该功能。代码如下:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 闰年二月份有 29 天,平年二月份有 28 天
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
days_of_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
else:
days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
print(f"{year}年{month}月有{days_of_month[month-1]}天")
```
这个程序首先读入用户输入的年份和月份,然后根据年份判断该年的二月份天数是 28 天还是 29 天,将每月天数保存在一个列表中,最后输出结果。
相关问题
c编写一个程序,输入年和月,输出该月有多少天
好的,以下是可以实现该功能的 C 代码:
```
#include <stdio.h>
int main() {
int year, month;
printf("请输入年和月:\n");
scanf("%d %d", &year, &month);
// 判断每月的天数
int days;
switch (month) {
case 2:
days = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
break;
}
printf("%d 年 %d 月共有 %d 天\n", year, month, days);
return 0;
}
```
程序通过输入年和月,使用 `switch` 语句判断该月有多少天,并输出结果。其中,涉及到闰年时,根据公历规定,只有符合以下两个条件之一的年份才是闰年:
1. 被4整除,但不被100整除;
2. 被400整除。
用c语言编写一个程序,输入年和月,输出该月有多少天
以下是一个用C语言编写的程序,根据输入的年和月,输出该月有多少天的代码示例:
```c
#include <stdio.h>
int main() {
int year, month, days;
printf("请输入年份和月份,以空格分隔:\n");
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("输入的月份不合法!\n");
return 1;
}
printf("%d 年 %d 月共有 %d 天。\n", year, month, days);
return 0;
}
```
这个程序首先提示用户输入年份和月份,然后通过 `scanf` 函数获取输入值。接下来使用 `switch` 语句判断月份,如果是 1、3、5、7、8、10 或 12 月,将“天数”变量 `days` 设置为 31;如果是 4、6、9 或 11 月,将 `days` 设置为 30;如果是 2 月,需要判断是否是闰年,如果是则将 `days` 设置为 29,否则设置为 28。
最后输出结果,格式化输出年、月和天数,并返回程序执行成功的状态码 0。如果输入的月份不合法,将提示用户并返回错误状态码 1。