|
|
发表于 2023-8-16 12:56:27
|
显示全部楼层
本楼为最佳答案
- #只考虑正数
- x = input()
- dot = x.find('.') #不确定小数点的位置,所以先获取小数点的索引
- if dot != -1 and int(x[dot+1]) > 4:
- #如果有小数点并且后一位大于4
- y = int(float(x)) + 1 #直接int()会报错,因为字符串中可能是个小数
- else:
- y = int(float(x))
- print(y)
复制代码
这一小段代码只考虑正数的情况,能够满足四舍五入的要求
但是,int函数在浮点数参数小于0时,结果会更靠近0
所以如果也要实现负数,可以选下面的代码:
- x = input()
- dot = x.find('.')
- if dot != -1 and int(x[dot+1]) > 4 and float(x) > 0:
- y = int(float(x)) + 1
- elif dot != -1 and int(x[dot+1]) > 4 and float(x) < 0:
- y = int(float(x)) - 1
- else:
- y = int(float(x))
- print(y)
复制代码 |
|