将sumt变量移动到while循环中,然后在sumt5 <= 0.00时退出循环:import decimal
def fact(n):
if n == 0:
return 1
else:
return n*(fact(n-1))
x = 1 # Hardcoded for this example, instead of prompting.
A = 0
summation = 1.0
while True:
sumt1 = A + 1
sumt2 = x**A
sumt3 = fact(A) # Was `fact(x)` in original code, which didn't match your formula & prevented `sumt5 <= 0.00` from ever being true.
sumt4 = sumt1 * sumt2
sumt5 = sumt4/sumt3
summation += sumt5
A += 1
if sumt5 <= 0.00:
break
finalsum=decimal.Decimal(summation)
print("The value is {}.".format(finalsum))
更新的答案
我想更好地了解发生了什么,所以我将求和分解成一个单独的函数,而不是单独计算所有的单独项,而是直接将它们插入到您在OP:((A+1)((X)^A))/A!中给出的函数中。我的代码是:
^{pr2}$
当我运行它时,我收到了以下输出:final == 6.43656365691809018159119659685529768466949462890625
final == 23.167168296791945891754949116148054599761962890625
final == 81.3421476927506574838844244368374347686767578125
final == 273.99075016572106733292457647621631622314453125
final == 891.478954615459542765165679156780242919921875
final == 2825.00155444914480540319345891475677490234375
final == 8774.06526742766800452955067157745361328125
final == 26829.62188337555198813788592815399169921875
final == 81031.839275753838592208921909332275390625
final == 242292.12374287386774085462093353271484375