問(wèn)題描述
今天我嘗試制作一個(gè)程序,詢問(wèn)用戶他/她希望我對(duì)系列中的多少項(xiàng)目求和.該系列將用于近似 pi 的值.到目前為止,這是我的代碼:
Today I tried to make a program that would ask a user how many items in a series he/she wanted me to sum. This series would be used to approximate the value of pi. Here is my code thus far:
from math import pi
def pi_sum():
n = eval(input("How many terms do you want to sum: "))
for i in range(n):
denominator= 2.0 * i + 1
sign = (-1) ** i
numerator = 4
result = (4 * sign) /denominator
print(result)
print(sum(result))
pi_sum()
但是,此代碼會(huì)生成錯(cuò)誤消息:
However, this code generates the error message:
File "C:/Users/Crisa/PycharmProjects/untitled/piprogram.py", line 14, in pi_sum
print(sum(result))
TypeError: 'float' object is not iterable
如果我的 for 循環(huán)生成浮點(diǎn)數(shù),我如何讓 python 對(duì)我的 for 循環(huán)中的值求和?我被卡住了:/
How can I get python to sum the values in my for loop if my for loop is generating floats? I am stuck :/
推薦答案
將每次迭代的結(jié)果添加到列表中:
Add your results of each iteration into a list:
myresults = []
for i in range(n):
...
myresults.append(result)
然后在最后,得到所有結(jié)果的列表總和:
Then at the end, get the sum of the list with all your results:
print(sum(myresults))
這篇關(guān)于求和.TypeError:“浮動(dòng)"對(duì)象不可迭代的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!