所以我有代码
def formula(n):
while(n < 11):
answera = 15/(-4)** n
print(answera)
n = n + 1
formula(1)
如何以高位顺序添加输出?
例如,
first_output = (the output of n = 1)
second_output = (the output of n = 1) + (the output of n = 2)
third_output = (the output of n = 1) + (the output of n = 2) + (the output of n = 3)
依旧......
答案 0 :(得分:3)
你需要在while循环之外定义变量answera
,以便它的shope应该存在于循环之外,这样当你返回值时,可以返回完全更新的值。这样的事情。
def formula(n):
answera = 0
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
print(answera)
formula(1)
现在它应该给你正确的结果。
答案 1 :(得分:1)
def formula(n):
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
这个想法是你需要在其中一个变量中累积15/(-4)**n
的值..(这里是answera)并继续打印出来。
我希望这能回答你的问题。
答案 2 :(得分:0)
你的问题有些含糊不清;你想要'answera'的总和,还是'公式'的总和?
如果'answera',那么你可以用“yield”替换“print”并调用“sum”:
def formula(n):
while(n < 11):
answera += 15/(-4)** n
yield answera
n = n + 1
sum(formula(2))
这使得'formula'成为generator,而“sum”将迭代该生成器直到它耗尽。
如果你想要多个'公式'调用的总和,那么按照KISS原则,用另一个函数包装你的函数:
# assuming that 'formula' is a generator like above
def mega_formula(iterations):
total = []
for i in range(1, iterations + 1): # b/c range indexs from zero
total.append(sum(formula(i))
return sum(total)