小编Kau*_*hik的帖子

使用while循环找到1 + 1/2 + 1/3 .... + 1 / n的和

这是我的作业问题。我们被要求找到级数的总和-> 1 + 1/2 + 1/3 + 1/4 ... + 1 / n(这里n = 20)

下面提供了我尝试过的代码。

denominator=1
num=float(1/denominator)
sum=0
while denominator<=20:
    print(num)
    sum+=num
    denominator+=1
print(f'the sum of the above series is {sum}.')
Run Code Online (Sandbox Code Playgroud)

输出结果为20。但这不是必需的结果。

python python-3.x

1
推荐指数
1
解决办法
345
查看次数

输出背后的原因是什么?

输入

x, y = 20, 60
y, x, y = x, y-10, x+10
print(x, y)
Run Code Online (Sandbox Code Playgroud)

输出

50 30
Run Code Online (Sandbox Code Playgroud)

我期望什么?

  • x = 20

  • y = 60

  • y = x = 20

  • x = y-10 = 20-10 = 10

  • y = x + 10 = 20

预期产量

10 20
Run Code Online (Sandbox Code Playgroud)

为什么不是这种情况?是因为首先对表达式求值,然后才给变量赋值?

python-3.x output

1
推荐指数
1
解决办法
37
查看次数

标签 统计

python-3.x ×2

output ×1

python ×1