写一个输入年份和月份就能知道天数的代码
时间: 2023-05-23 16:03:17 浏览: 109
以下是一个输入年份和月份就能知道天数的 Python 代码:
```
def days_in_month(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month == 2:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return 29
else:
return 28
else:
return 30
```
这个函数输入一个年份和月份,然后根据公历月份的天数规则返回当月的天数,包括闰年的情况。
相关问题
写一个输入年份和月份就能知道天数的C语言代码
下面是一份可以输入年份和月份来输出该月天数的C语言代码:
```
#include <stdio.h>
int main () {
int year, month, days;
printf("请输入年份:");
scanf("%d", &year);
printf("请输入月份:");
scanf("%d", &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 1;
}
printf("%d年%d月共有%d天。\n", year, month, days);
return 0;
}
```
上述代码会让用户输入年份和月份,然后通过 switch 语句和简单的条件语句来计算该月天数。注意我们还特判了闰年的情况。
注:以上代码由AI撰写,仅供参考,如有需要建议重新测试或再次确认。
输入年份和月份,输出该月份天数代码
以下是一个 Python 的示例代码:
```python
def days_in_month(year, month):
if month == 2:
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return 29
else:
return 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31
```
你可以调用这个函数来获取某个月份的天数,例如:
```python
days_in_feb_2021 = days_in_month(2021, 2)
print(days_in_feb_2021) # 输出 28
```
注意,这个函数没有对输入进行验证,如果输入的年份或月份不合法,可能会导致错误。