本帖最后由 jackz007 于 2018-9-16 09:21 编辑
楼主的代码判断闰年的逻辑是:
if <temp 能被 400 整除>
temp 是闰年
else
if <temp 可以被 4 整除> 同时 <temp 不可以被 100 整除>
temp 是闰年
else
temp 不是闰年
用语言来表述就是:能被 400 整除的年份都是闰年;其余的年份,能被 4 整除但不能被 100 整除的年份也都是闰年;再其余的年份就都不是闰年。
这样判断闰年在逻辑上虽然没有问题,但是可以更加简练一些。以下是在 Python 2.7 环境中编写的代码
- #!/usr/bin/python
- #coding:gbk
- temp = raw_input('请输入一个年份:')
- while not temp.isdigit():
- temp = raw_input('抱歉,您的输入有误,请输入一个整数:')
- year = int(temp)
- if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
- print(temp + ' 是闰年!')
- else:
- print(temp + ' 不是闰年!')
复制代码