|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python FAQ 046 判断闰年程序总是输出 “不是闰年”
问题
为什么下面的代码不能正确判断是否为闰年啊?
- temp = input("please input:")
- if not temp.isdigit():
- print("wrong type")
- else:
- year = int(temp)
- a = year / 4
- b = year / 100
- c = year / 400
- if isinstance(c, int):
- print("闰年")
- else:
- if isinstance(a, int) and isinstance(b, float):
- print("闰年")
- else:
- print("不是闰年")
复制代码
解答
因为 Python 除法无论结果是否为整数,结果都为浮点数:
- >>> 5 / 2
- 2.5
- >>> 4 / 2
- 2.0
复制代码
导致 isinstance() 那块判断永远都为 False。
建议用取余运算符判断是否能够整除:
- temp = input("please input:")
- if not temp.isdigit():
- print("wrong type")
- else:
- year = int(temp)
- a = year % 4
- b = year % 100
- c = year % 400
- if not c:
- print("闰年")
- else:
- if not a and b:
- print("闰年")
- else:
- print("不是闰年")
复制代码 |
评分
-
查看全部评分
|