【问题标题】:Sum of Even and Odd numbers includes numbers on outside of range, if if not even or odd偶数和奇数之和包括超出范围的数字,如果不是偶数或奇数
【发布时间】:2020-09-04 17:42:46
【问题描述】:

所以这是我学习计算机科学的第一个学期,而我目前正在学习 Python。我的任务是创建一个程序来显示您选择的整数之间的奇数和偶数之和。它几乎可以工作,除了它添加了定义为范围的数字,而不仅仅是其中的赔率或偶数。谁能指出我做错了什么?我已经坚持了一段时间了。感谢您的帮助!

我已经定义了范围并使用 sum 函数来查找总和,但是我用于范围的值包括在内。

enter code here
print("Welcome to my Odd/Even sum generator.")
print("This program will show you the sum of all even and odd numbers between two integers of your choice.")
Num1 = int(input("What is your first, lower integer?"))
Num2 = int(input("What is your second, higher integer?"))


def sum_even(Num1, Num2):
    count1 = 0
    for i in range(Num1, Num2+1):
        if(i % 2 == 0):
            count1 += i
    return count1

def SumOdds(Num1,Num2):
  count2= Num1 + Num2 
  for i in range(Num1,Num2+1):
     if(i == Num1 or i == Num2):
         pass
     elif (int(i%2==1)):
        count2=count2+i

  print("The sum of the odd numbers is",(count2),".")
SumOdds(Num1,Num2)
print("The sum of the even numbers is",(sum_even(Num1, Num2)),".")

只有当这些范围值适用于奇数/偶数和时,我才希望它添加范围值。比如说,我输入了一个 5 和 25 的范围。我希望范围值包含在 OddSum 的总和中,而不是 EvenSum 的总和中。

【问题讨论】:

  • sum_even 看起来是正确的。只需复制/粘贴它(并否定内部 if 条件),您应该可以使用 SumOdds。稍后,当您熟悉该语言时,您会发现可以在一行代码中编写每个函数:)。
  • 如删除if语句?
  • 不,negatedelete 不是相同的东西:if(i % 2 != 0):
  • 做到了!非常感谢,我们的教练已经走了整整一个星期,所以我没有人能摆脱它。非常感谢!
  • 我不确定我是否理解您的问题。如果您在从 1 到 10 的范围内进行计算,您是否会期望 110 在总和中?大概1 只会是奇数(因为它是奇数),而10 会是偶数(因为它是偶数)。但这些都不需要特殊处理。你能举例说明你的输入和你的代码做错事时你期望的输出吗?

标签: python python-3.x sum


【解决方案1】:

您的问题是您在 SumOdds 中放置了以下代码。

for i in range(Num1,Num2+1):
     if(i == Num1 or i == Num2):
         pass

这会跳过第一个和最后一个数字,但如果您将其移至 sum_evens,您的代码应该可以按预期工作。

【讨论】:

    【解决方案2】:

    您的代码看起来很棒,对您有帮助的更改如下:

    def SumOdds(Num1,Num2):
        count2 = 0 # here ur adding NUM1+NUM2 by defualt initial it must be zero
        for i in range(Num1,Num2+1):
            if(i == Num1 or i == Num2):
                continue #If you don't want to consider the start and end so you can use continue 
            if (int(i%2==1)):
                count2+=i
        print(f"The sum of the odd numbers is: {count2}") # if your using above 3.5 python so u can use this type of formating also.
    
    def sum_even(Num1, Num2):
        count1 = 0
        for i in range(Num1, Num2+1):
            if(i == Num1 or i == Num2):
                continue #If you don't want to consider the start and end so you can use continue 
            if(i % 2 == 0):
                count1 += i
        return count1
    
    sum_of_odd = sum(filter(lambda x: (x % 2 != 0), range(Num1, Num2+1))) # Another way of doing
    sum_of_even = sum(filter(lambda x: (x % 2 == 0), range(Num1, Num2+1))) #Another way of doing 
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多