编写一个程序,根据输入的年份和月份,计算该月有多少天
时间: 2023-03-10 17:37:27 浏览: 168
可以使用以下算法来计算每月天数:1. 如果月份是1、3、5、7、8、10、12,则每月有31天;2. 如果月份是4、6、9、11,则每月有30天;3. 如果月份是2,且年份是闰年,则每月有29天;4. 如果月份是2,且年份不是闰年,则每月有28天。
相关问题
编写一个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;
}
```
该程序使用了 switch 语句来根据月份计算天数,对于闰年的判断使用了 if 语句。
python编写程序输入年份和月份判断输入的月份有多少天
可以采用Python中的datetime模块来实现该功能。具体代码如下:
```python
import datetime
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 获取下一个月的第一天
next_month = datetime.datetime(year, month, 1) + datetime.timedelta(days=31)
# 通过计算下一个月的第一天减去一天得到当月的最后一天
last_day = (next_month - datetime.timedelta(days=next_month.day)).day
print("{}年{}月有{}天".format(year, month, last_day))
```
这个程序会先让用户输入年份和月份。然后,它会创建一个datetime对象,表示输入的年份和月份。接着,我们通过计算下一个月的第一天减去一天的方式来获取当月的最后一天。最后,程序输出结果,告诉用户输入的年份和月份有多少天。