2

我需要我的输出为小数点后 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) 方法,我都会不断收到语法错误。有人知道我哪里出错了吗?

谢谢!

4

4 回答 4

2

您不需要,打印功能就%足够了,例如:

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

喜欢:

print("The RMS distance from the starting point is %.3f" % totalSum)
于 2013-05-30T19:22:45.510 回答
1

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

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

如果您使用更现代的方式,那就更明显了format

print ("The average distance from the starting point is a {:.3f}".format(pos1))
于 2013-05-30T19:22:19.553 回答
0

字符串文字和 % 符号之间有逗号。删除那些。

print("The average distance from the starting point is a %.3f" % pos1)
于 2013-05-30T19:22:20.880 回答
0

您对printand 格式感到困惑:

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

不过,您应该真的更喜欢新的样式格式:

print("Whatever {:.3f}".format(pos1))

或者,如果你真的想要:

print("Whatever", format(pos1, '.3f'))
于 2013-05-30T19:22:23.003 回答