gpt4 book ai didi

python - 格式化我的小数时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:25 26 4
gpt4 key购买 nike

我需要我的输出保留 3 位小数

def main():

n = eval(input("Enter the number of random steps: "))
t = eval(input("Enter the number of trials: "))

pos = 0
totalPosition = 0
totalSum = 0
L = list()

import random
A = [-1, 1]

for x in range(t):
pos = 0
for y in range(n):
step = random.choice(A)
pos += step


totalPosition += abs(pos)
totalSum += pos**2

pos1 = totalPosition/t
totalSum /= t
totalSum = totalSum**0.5


print("The average distance from the starting point is a %.3f", % pos1)
print("The RMS distance from the starting point is %.3f", % totalSum)

main()

无论我尝试同时使用 '%' 字符还是 {0:.3f} .format(pos1) 方法,我都会不断收到语法错误。有人知道我哪里出错了吗?

谢谢!

最佳答案

你不需要 , 在打印函数中只需要 % 例如:

print("The RMS distance from the starting point is %.3f", % totalSum)
^ remove this ,

喜欢:

print("The RMS distance from the starting point is %.3f" % totalSum)

关于python - 格式化我的小数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16844226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com