编写自定义方法,传递年份、月份,返回该月的天数。
时间: 2024-05-09 15:19:29 浏览: 10
以下是Java语言的实现:
```java
public static int getDaysOfMonth(int year, int month) {
int days = 0;
switch (month) {
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
return days;
}
```
该方法首先通过switch语句判断传入的月份,对于2月份特殊处理,判断是否为闰年,如果是则返回29天,否则返回28天,对于其他月份直接返回对应的天数。注意闰年的判断方法是:能被4整除但不能被100整除,或者能被400整除。
相关问题
用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("请输入月份:"))
# 判断该年份是否为闰年
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
# 计算该月的天数
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
if is_leap:
days = 29
else:
days = 28
# 输出结果
print("{0}年{1}月的天数为:{2}".format(year, month, days))
```
你可以将以上代码复制到 Python 环境中运行,然后输入年份和月份,即可得到该月的天数。