这个问题要求编写一个程序,使用forumla pi =4/1-4/3+4/5-4/7+…
我必须提示用户列中的术语数,并计算近似值。这就是我试过的程序
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“将以红色高亮显示。
发布于 2015-06-09 21:02:46
您忘记了这行末尾的冒号:
for i in range(1, n+1):
^ missing每当您在看起来正确的行上出现语法错误时,尝试在错误之前查看行,以确定是否正确。
您还忘记了这行末尾的):
n = eval(input("Enter the number of terms you want in the approximation: ")发布于 2015-06-09 21:03:39
缺少操作符*:
term = 4/(2n+1)更改为
term = 4/(2*n+1)发布于 2015-06-09 21:02:51
你错过了":“在for语句的末尾:
for i in range(1, n+1):
term = 4/(2*n+1)
dummy = dummy + ((-1)**n) * termhttps://stackoverflow.com/questions/30742724
复制相似问题