格式化我的小数有困难吗

2024-06-07 04:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要我的输出是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)方法,都会遇到语法错误。有人知道我哪里错了吗?在

谢谢!在


Tags: oftheinposnumberforinputmain
3条回答

对于字符串插值,需要将%运算符放在格式字符串后面:

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

如果您使用更现代的format方式,则更明显:

^{pr2}$

在print函数中不需要,,只要%就足够了,例如:

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

比如:

^{pr2}$

字符串文字和%符号之间有逗号。把那些拿走。在

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

相关问题 更多 >