python-3.x - 四舍五入一个元组
问题描述
无法弄清楚如何将元组的最终输出四舍五入到小数点后 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())
解决方案
您需要做的就是在返回时对它们进行四舍五入,或者在定义变量时对其进行四舍五入。您也可以完全跳过变量,但性能会有所提高(我认为)。
对于正常舍入(用此替换 return 语句):
return (round(a, 2), round(b, 2))
或者,您可以这样做:
return (round(sum(result) / len(result), 2), round(max(result), 2))
推荐阅读
- reactjs - 登录后重定向路由器
- sql-server - SQL:使用 EXEC sys.sp_updateextendedproperty 添加 getdate() 作为扩展属性
- python - Python dist-packages 权限
- node.js - 类型错误:未定义不是函数 - node.js
- single-sign-on - 会话验证端点在 AM5 中有效,但在 AM6 中无效
- pipe - 管道解压缩文件到 mongoimport
- python - 如何在数据框中使用 re.search 列
- javascript - 从第二次获取 fetch 结果
- fortran - Fortran中的可变长度参数列表?
- java - 通过 XQuery 和 Saxon 加载外部 java 函数