【问题标题】:Using a For loop to find the sum of positive even numbers and negative odd numbers in python使用For循环在python中查找正偶数和负奇数的总和
【发布时间】:2018-10-16 19:55:51
【问题描述】:

有一个问题要求找到正偶数和负奇数之和,1 到 100(所以 1+2-3+4....+98-99+100)。这是我到目前为止所做的,如果我的数学运算正确,正确的总和应该是 52,但我得出的总和是 50。有什么建议吗?

lst = range(1,101)
>>> total = 0
>>> for x in lst:
...     if x % 2:
...             total -= x
...     else:
...             total += x
...
>>> total
50

【问题讨论】:

  • 为什么你认为这等于 52? sum(range(2, 101, 2)) - sum(range(1, 100, 2)) == 50。或者只是数学,2+100 == 4+98 == ... = 102*251+99 == 3+97 == ... = 100*25,所以 102*25 - 100*25 = 50
  • 您的代码与您的过期输出不匹配。 1+2-3+4...+98-99+100, 1 根据你的描述应该是-1

标签: python-2.7 for-loop


【解决方案1】:

我相信您的代码是正确的,而您的数学是错误的。以下是解决问题的三种方法。

你的解决方案:

lst = range(1,101)
total = 0
for x in lst:
    if x % 2:
        total -= x
    else:
        total += x
print(total)

50

偶数之和加上奇数之和:

def sumForLoop(max):
    positiveEven = sum(range(2,max+1,2))
    negativeOdd = -sum(range(1,max+1, 2))
    print(positiveEven + negativeOdd)
sumForLoop(100)

50

总计公式:

def sumFormula(max):
     print(-1**100 *math.floor(max/2))
sumFormula(100)

50

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2022-11-25
    • 2011-09-28
    相关资源
    最近更新 更多