2015-09-05 114 views
-2

因此,我写了这段代码,但它似乎不起作用。循环(1 + x + x ** 2 + x ** 3 + x ** 4 .... n)不起作用

x=1 
sum1=0 
n=int(input("enter how long the series should be")) 
print (x) 
for a in range (1,n): 
    sum1=sum1+(sum1**a) 
    print(sum1) 
    a=a+1 
print("the sum of the series is",sum1) 

输出是:你不使用你的输入x

enter how long the series should be5 
1 
0 
0 
0 
0 
the sum of the series is 0 
>>> 
+2

你并不需要增加'了' –

+0

你不想'X **了'? – jtbandes

+0

谢谢大家。 –

回答

3

公告中的任何地方循环。这是因为sum1 ** a应该是x ** a。另外,您希望使用range(1, n+1),因为第二个参数需要比您想要生成的最大值大一个。

增量a因为你是无害的,但没有必要; for循环本身在每次迭代中更新a的值。在你的公式sum1=sum1+(sum1**a)(递增a在循环的顶部会造成问题,因为当你在计算中使用它a会有错误的值。)

+1

还提到他不需要在循环中增加'a',范围必须是从1到* n + 1 * –

0

使用X。 所以修改后的EQ应该sum1=sum1+(x**a)

x=1 
sum1=0 

n=int(input("enter how long the series should be")) 
    print (x) 
    for a in range (1,n): 
    sum1=sum1+(x**a) 
    print(sum1) 
    a=a+1 
print("the sum of the series is",sum1) 
+1

请更改您的句子(意思是有些翻转)并更正python缩进。 –

+0

@HuguesFontenelle表示感谢。 –

+0

不幸的是......我会发布我自己的答案,然后.. –

0
x=1 
sum1=0 
n=int(input("enter how long the series should be")) 
print (x) 
for a in range (1,n): 
    sum1 += (x**a) 
    print(sum1) 
print("the sum of the series is", sum1) 
+1

这不回答海报的问题;这个答案只是代码,并没有提供任何指导,为什么这个工程和海报的代码没有。 – Foon