本文介紹了求和.TypeError:“浮動"對象不可迭代的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
今天我嘗試制作一個程序,詢問用戶他/她希望我對系列中的多少項目求和.該系列將用于近似 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()
但是,此代碼會生成錯誤消息:
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 循環生成浮點數,我如何讓 python 對我的 for 循環中的值求和?我被卡住了:/
How can I get python to sum the values in my for loop if my for loop is generating floats? I am stuck :/
推薦答案
將每次迭代的結果添加到列表中:
Add your results of each iteration into a list:
myresults = []
for i in range(n):
...
myresults.append(result)
然后在最后,得到所有結果的列表總和:
Then at the end, get the sum of the list with all your results:
print(sum(myresults))
這篇關于求和.TypeError:“浮動"對象不可迭代的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!