Skip to main content
 首页 » 编程设计

python之尝试用 python 编写 "1-x+x^2-x^3+x^4-x^5..."系列,有人有什么想法吗

2025年05月04日14webabcd

我正在尝试编写一个 python 脚本来计算以下系列:

1-x+x^2-x^3+x^4...

如果有人可以提供一些关于如何使这项工作适用于任何 n 值的指导,我将不胜感激?

到目前为止,我只能通过对所有操作进行硬编码来做到这一点 :D

提前致谢!

我目前的解决方案:

def seriesrun(x,n): 
    ncurrent = 0 
    total = 1 
    while ncurrent <= n: 
        if ncurrent == 0: 
            ncurrent = ncurrent + 1 
            total = total * 1 
            print(ncurrent, total) 
        elif ncurrent == 1: 
            ncurrent = ncurrent + 1 
            total = total - x 
            print(ncurrent, total) 
        elif ncurrent == 2: 
            ncurrent = ncurrent + 1 
            total = total + x**2 
            print(ncurrent, total) 
        elif ncurrent == 3: 
            ncurrent = ncurrent + 1 
            total = total - x**3 
            print(ncurrent, total) 
        elif ncurrent == 4: 
            ncurrent = ncurrent + 1 
            total = total + x**4 
            print(ncurrent, total) 
        elif ncurrent == 5: 
            ncurrent = ncurrent + 1 
            total = total - x**5 
            print(ncurrent, total) 
    return total 
 
x = int(input('What is your starting x value?\n')) 
n = 5 
# n = int(input('How far should the series go?')) 
# the current n position you are at... 
 
print('Final answer is: '+str(seriesrun(x,n))) 

请您参考如下方法:

你可以试试:

series = 0 
pow = 0 
while True: 
    series += (-1*x)**pow 
    pow += 1 

这是一个无限循环,因此您可以添加退出条件。

编辑:忘记交替符号