鱼C论坛

 找回密码
 立即注册
查看: 825|回复: 4

求解:课后代码修改

[复制链接]
发表于 2018-1-15 19:26:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大神:

课后有一个判断闰年的代码:
temp = input('请输入一个年份:')
while not temp.isdigit():
    temp = input("抱歉,您的输入有误,请输入一个整数:")

year = int(temp)
if year/400 == int(year/400):
    print(temp + ' 是闰年!')
else:
    if (year/4 == int(year/4)) and (year/100 != int(year/100)):
        print(temp + ' 是闰年!')
    else:
        print(temp + ' 不是闰年!')

我想加入 如果输入年份不是闰年的 循环和次数,不知该如何写?做过如下尝试,但是不行:
times = 3
temp = input('请输入一个年份:')
while not temp.isdigit():
    temp = input('请输入一个整数:')

year = int(temp)
while (not year/400 == int(year/400) or\
((year/4 == int(year/4)) and (year/100 != int(year/100))))\
and (times > 0):
  print(temp + '不是闰年')
  print('再试一次:')
  if times < 1:
    print('机会用完了')
        
    times = times - 1


print('游戏结束')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-1-15 19:45:11 | 显示全部楼层
你这里循环应该加在最外层,要把input输入部分包含进去,不然无论怎么循环年份都不会变,因为没有输入新年份
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-15 19:49:16 | 显示全部楼层
本帖最后由 Zmynx_2017 于 2018-1-15 19:50 编辑
  1. times = 3
  2. temp = input('请输入一个年份:')
  3. while not temp.isdigit():
  4.     temp = input('抱歉,您的输入有误,请输入一个整数:')
  5. year = int(temp)
  6.    
  7. while (not year/400 == int(year/400) or\
  8.        ((year/4 == int(year/4)) and (year/100 != int(year/100))))and (times > 0):
  9.     print(temp + '不是闰年')
  10.     times -= 1
  11.     if times>=1:
  12.         print('再试一次:')
  13.         temp = input('请输入一个年份:')
  14.         while not temp.isdigit():
  15.             temp = input('抱歉,您的输入有误,请输入一个整数:')
  16.         year = int(temp)
  17.     if times < 1:
  18.         print('机会用完了')
  19. print('游戏结束')
复制代码

输入闰年直接结束,非闰年会继续输入,可输入三次。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-15 19:53:01 | 显示全部楼层
  1. time = 3
  2. while(time >0):
  3.     n = input('please input a number:')

  4.     if n.isdigit() == False:
  5.         print('input error')
  6.         continue
  7.     i=int(n)
  8.     if i%4!=0:
  9.         print(n+'不是闰年')
  10.         time-=1
  11.     elif i%100==0 and i%400!=0:
  12.         print(n+'不是闰年')
  13.         time-=1
  14.     else:
  15.         print(n+'是闰年')
  16.         time = 3
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-1-16 10:44:14 | 显示全部楼层
感谢orino指出问题并帮助重写了更简洁的代码! 感谢Zmynx_2017 在我代码的基础上找出问题并修改!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 07:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表