|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目:第五节课后题动动手1.写一个程序,判断给定年份是否为闰年。(注意:请使用已学过的 BIF 进行灵活运用).这样定义闰年的:能被4整除但不能被100整除,或者能被400整除都是闰年。
我的解答:
temp = input("请输入年份数字:")
while not temp.isdigit():
temp = input("抱歉,您的输入有误,请输入一个整数:")
year = int(temp)
if isinstance(year/400,int):
print("闰年")
else:
if isinstance(year/4,int) and not isinstance(year/100,int):
print("闰年")
else:
print("不是闰年")
这个解法经实例2000(系统给出结果:不是闰年)验证明显不对,百思不得骑姐~初学小白求助大神
isinstance 函数是判断 第一参数对象 是否属于 第二参数的实例,而 Python 中只要使用 / 除法,那么得到的结果就一定为 浮点型
例如:
- >>> a = 10
- >>> b = a / 2
- >>> print(b)
- 5.0
- >>> print(type(b))
- <class 'float'>
复制代码
所以这里 isinstance 不管 year 为多少,始终都为 float 型则导致 if 条件始终不成立,所以我们这儿不能用 isinstance 函数
可以用 % 求余来判断是否被整除:
- temp = input("请输入年份数字:")
- while not temp.isdigit():
- temp = input("抱歉,您的输入有误,请输入一个整数:")
- year = int(temp)
- if not year % 400:
- print("闰年")
- else:
- if not year % 4 and year % 100:
- print("闰年")
- else:
- print("不是闰年")
复制代码
也可以与 int 转化后的值进行比较,看下两值是否相等:
- temp = input("请输入年份数字:")
- while not temp.isdigit():
- temp = input("抱歉,您的输入有误,请输入一个整数:")
- year = int(temp)
- if year/400 == int(year/400):
- print("闰年")
- else:
- if year/4 == int(year/4) and year / 100 != int(year/100):
- print("闰年")
- else:
- print("不是闰年")
复制代码
|
|