Shi*_*ndi 2 python rounding floor ceil
我有一个这个小任务,我将数字四舍五入到十的更高倍数。但是想要将其四舍五入到最接近的十的倍数。
我的代码:
import math
a = map(int,list(str(7990442)))
b = map(int,list(str(1313131)))
print "a :",a
print "b :",b
l= []
for p,q in zip(a,b):
l.append(p*q)
print "prod list :",l
ls = sum(l)
print "sum :",ls
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
top = roundup(ls)
print "round value: ",top
val = top-ls
print "val :",val
a.append(val)
print "output :",a
Run Code Online (Sandbox Code Playgroud)
输出 :
a : [7, 9, 9, 0, 4, 4, 2]
b : [1, 3, 1, 3, 1, 3, 1]
prod list : [7, 27, 9, 0, 4, 12, 2]
sum : 61
round value: 70
val : 9
output : [7, 9, 9, 0, 4, 4, 2, 9]
Run Code Online (Sandbox Code Playgroud)
预期输出:
sum : 61
round value: 60
val : 1
output : [7, 9, 9, 0, 4, 4, 2, 1]
Run Code Online (Sandbox Code Playgroud)
您可以使用round(x / 10.0) * 10代替math.ceil.
更容易
def custom_round(x):
return int(round(x, -1))
Run Code Online (Sandbox Code Playgroud)
这立即四舍五入到十的倍数。
| 归档时间: |
|
| 查看次数: |
4772 次 |
| 最近记录: |