首页 > 解决方案 > 四舍五入一个元组

问题描述

无法弄清楚如何将元组的最终输出四舍五入到小数点后 2 位。有什么建议么???我的代码如下:

import random
random.randint(0,10)

def a():
    counter=0
    result=[]
    total_score = 0

while(counter<10000):
    i = random.randint(0,10)
    while i not in [1,2,3]:
        if i in [4,5,6]:
            total_score = total_score + i
            i=random.randint(0,10)
        elif i in [7,8,9,10]:
            total_score = total_score + i*2
            i=random.randint(0,10)
        else: 
            total_score = total_score/2
            i=random.randint(0,10)
    counter += 1
    result.append(total_score)

a=sum(result)/len(result)
b=max(result)
return(a,b)

print(a())

标签: python-3.xtuplesrounding

解决方案


您需要做的就是在返回时对它们进行四舍五入,或者在定义变量时对其进行四舍五入。您也可以完全跳过变量,但性能会有所提高(我认为)。

对于正常舍入(用此替换 return 语句):

return (round(a, 2), round(b, 2))

或者,您可以这样做:

return (round(sum(result) / len(result), 2), round(max(result), 2))

推荐阅读