编写一个判断闰年的函数leapyear(),输入年份,返回该年份是否为闰年。
时间: 2024-05-14 15:17:58 浏览: 18
好的,以下是Python的实现代码:
```python
def leapyear(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
```
这个函数的实现方法是根据闰年定义来判断,闰年的定义是:能够被4整除但不能被100整除,或者能够被400整除。根据这个定义,我们可以编写上面的代码。如果输入的年份是闰年,函数返回True,否则返回False。
相关问题
matlab编写一个函数 project1.m,其功能是判断某一年是否为闰年
好的,以下是一个判断闰年的 Matlab 函数示例:
```matlab
function leapYear = project1(year)
% 判断某年是否为闰年
% 输入参数:
% year: 待判断的年份,格式为整数
% 输出参数:
% leapYear: 若输入年份为闰年,则返回 1;否则返回 0
if mod(year, 4) == 0
% 能被 4 整除
if mod(year, 100) == 0
% 能被 100 整除
if mod(year, 400) == 0
% 能被 400 整除
leapYear = 1;
else
leapYear = 0;
end
else
% 不能被 100 整除
leapYear = 1;
end
else
% 不能被 4 整除
leapYear = 0;
end
```
你可以将上述代码保存为 project1.m 文件,并在 Matlab 命令行界面中输入 `leapYear = project1(2020)` 等调用该函数来测试。
定义一个函数leapyear,判断一个年份是否是闰年。在主函数中输入一个年份,输出它是否是闰年。 闰年判定标准:年份能被4整除,但不能被100整除;或者年份能被400整除; 测试用例1: 输入: 2018 输出: 2018不是闰年 测试用例2: 输入: 2024 输出: 2024是闰年
好的,以下是一个 Python 代码示例,实现了上述要求:
```python
def leapyear(year):
"""
判断一个年份是否是闰年
"""
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
# 从键盘输入一个年份
year = int(input("请输入一个年份:"))
# 调用自定义函数判断是否是闰年
if leapyear(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
```
你可以将以上代码复制到 Python 编辑器中运行,输入一个年份,即可判断它是否是闰年。这段代码中的 `leapyear` 函数实现了判断一个年份是否是闰年的功能,通过 `if-else` 语句判断是否符合闰年的定义。如果是闰年,函数返回 `True`,否则返回 `False`。在主函数中,我们首先输入一个年份,然后调用 `leapyear` 函数进行判断,最后输出判断结果。