2013-05-30 69 views
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)方法。有人知道我要去哪里错了吗?

谢谢!

+0

不要使用'eval'为此,使用直接类型转换:'INT(输入('...'))' –

回答

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)) 
+0

每当我做{:.3f}的方式,我得到的语法错误,它突出显示格式 –

+0

之前的时间段,我想明白了。我不太喜欢python至少说哈哈,但我在学习。谢谢你的帮助! –

+0

@YotamKasznik Yotam在stackoverflow上表示感谢的最好方式是投票。托马斯给出了一个好方法...再试一次!它更友好。 –

0

您在字符串文字和%符号之间有逗号。删除这些。

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

哦男人,谢谢你,谢谢你现在的工作 –

0

你得到print和格式困惑:

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

你真的应该,虽然更喜欢新的样式格式:

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

或者,如果你真的想:

print("Whatever", format(pos1, '.3f')) 
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

是的!谢谢你 –

+0

@YotamKasznik欢迎Yotam,我相信你会喜欢这个[**字符串格式化在Python **中](http://stackoverflow.com/questions/517355/string-formatting-in-python )...有趣 –