鱼C论坛

 找回密码
 立即注册
查看: 5006|回复: 3

[已解决]课后题求助

[复制链接]
发表于 2023-8-16 12:56:27 | 显示全部楼层    本楼为最佳答案   
  1. #只考虑正数
  2. x = input()
  3. dot = x.find('.')  #不确定小数点的位置,所以先获取小数点的索引
  4. if dot != -1 and int(x[dot+1]) > 4:
  5.     #如果有小数点并且后一位大于4
  6.     y = int(float(x)) + 1  #直接int()会报错,因为字符串中可能是个小数
  7. else:
  8.     y = int(float(x))
  9. print(y)
复制代码

这一小段代码只考虑正数的情况,能够满足四舍五入的要求
但是,int函数在浮点数参数小于0时,结果会更靠近0
所以如果也要实现负数,可以选下面的代码:
  1. x = input()
  2. dot = x.find('.')
  3. if dot != -1 and int(x[dot+1]) > 4 and float(x) > 0:
  4.     y = int(float(x)) + 1
  5. elif dot != -1 and int(x[dot+1]) > 4 and float(x) < 0:
  6.     y = int(float(x)) - 1
  7. else:
  8.     y = int(float(x))
  9. print(y)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-4-1 17:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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