近似pi的程序

时间:2015-06-09 21:00:09

标签: python python-3.x

这个问题要求使用forumla pi = 4/1 - 4/3 + 4/5 - 4/7 + .....写一个近似pi的程序。

我必须提示用户输入系列中的术语数量,并计算近似值。这是我试过的程序

import math

def main():

     dummy = 4.0
     term = 0.0
     n = 0.0

     print("This program approximates the value of pi")
     n = eval(input("Enter the number of terms you want in the approximation: ")


     for i in range(1, n+1)
              term = 4/(2n+1)
              dummy = dummy + ((-1)**n) * term

     print("The approximation is ", dummy)
     print("The difference between pi and the approximation is ", math.sqrt((math.pi - dummy)**2))

但是,当我尝试运行它时,我收到错误消息“语法无效”,变量“term”以红色突出显示。

3 个答案:

答案 0 :(得分:2)

此处缺少运营商*

term = 4/(2n+1)

更改为

term = 4/(2*n+1)

答案 1 :(得分:1)

你忘记了这一行末尾的冒号:

for i in range(1, n+1):
                      ^ missing

每当您在看起来正确的行上出现语法错误时,请尝试查看错误之前行,以查看 是否正确。

您还忘记了此行末尾的)

     n = eval(input("Enter the number of terms you want in the approximation: ")

答案 2 :(得分:1)

你想念":"在for语句结束时:

for i in range(1, n+1):
          term = 4/(2*n+1)
          dummy = dummy + ((-1)**n) * term