【问题标题】:How can I get the sum of the outputs of an equation from a for loop? [duplicate]如何从 for 循环中获取方程输出的总和? [复制]
【发布时间】:2021-10-04 10:09:09
【问题描述】:

我知道如何获得一个范围内的数字之和,但如果我有一个写在 for 循环中的等式,如下所示:

for t in range(0,6):
    velocity = (.2*(t**2)) + 3

如何让 Python 将方程的所有输出相加?

【问题讨论】:

  • 一条线解决方案:sum(0.2 * (t ** 2) + 3 for t in range(6))

标签: python python-3.x


【解决方案1】:

只需将每次迭代得到的velocity的值相加如下:

velocity = 0
for t in range(0,6):
    velocity += (.2*(t**2)) + 3
print (velocity)

输出:

29.0

【讨论】:

    【解决方案2】:

    只需将公式的结果添加到 for 循环外定义的变量中

    sum_velocity = 0 
    
    for t in range(0,6):
        sum_velocity += (.2*(t**2)) + 3
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多