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

时间:2013-05-30 19:20:26

标签: 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)方法,我都会遇到语法错误。有谁知道我哪里出错了?

谢谢!

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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))

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

你得到了print并且格式混乱了:

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

你应该更喜欢新的格式格式:

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

或者,如果你真的想要:

print("Whatever", format(pos1, '.3f'))