Python3 -像这样四舍五入组合



我有一个浮点数组合(min_number, max_number),我期待以下四舍五入:

(-19.12, 34.45) "rounded to" (-19.2, 34.5)
(-0.34, -0.22) "rounded to" (-0.4, -0.3)
(-0.58, -0.87) "rounded to" (-0.6, -0.9)
(-0.24, 5.98) "rounded to" (-0.3, 6.0)
(2.57, 22.38) "rounded to" (2.6, 22.4)

注意,只需要1位小数。然后:

size = int(input('please input: '))
number = (min_number + max_number) / size

那么"number"也需要四舍五入,也需要小数点后1位:

10.233333 "rounded to" 10.3
5.744542267888 "rounded to" 5.8

任何想法吗?多谢,

只需乘以10,四舍五入并除以10

import math
num = input("Round a number:")
num = num.split()
print( math.ceil( float(num[0]) * 10 ) / 10,  math.ceil( float(num[1]) * 10 ) / 10 )

注意:正如@0 0所指出的,这对负数不起作用,如果你想对负数进行四舍五入,那么你需要为它们添加if语句,并使用math.floor

最新更新