简体   繁体   English

奇数和偶数

[英]Odd and Even Number

I am getting an error when calculating odd and even numbers in range 2008 2009 2010 and 2011. Actually this code for calculate the winner of team A, every odd year the team will win.在计算 2008 2009 2010 和 2011 范围内的奇数和偶数时出现错误。实际上,此代码用于计算 A 队的获胜者,每个奇数年该队都会获胜。 That why, in my code when its odd year, it will +1.这就是为什么,在我的代码中,当奇数年时,它会 +1。

i = 0
sum = 0

n = list(map(int, input("Year : ").split()))
for i in n :
    if i % 2 != 0 :
        sum += 1
    else :
        sum = 0
print("Win :", sum)

# Input
2008 2009 2010 2011
# Output
1 (This is the problem, it should be 2 wins but i dont know why the output is always 1)

I think you don't need else:sum = 0 .我认为您不需要else:sum = 0 You can continue with你可以继续

i = 0
sum = 0

n = list(map(int, input("Year : ").split()))
for i in n :
    if i % 2 != 0 :
        sum += 1
  
print("Win :", sum)

A juanpa_arrivillaga tried to get you to notice, when you encounter an even year, you are setting the sum to 0. When it's an odd year, you are incrementing sum.一个 juanpa_arrivillaga 试图让你注意到,当你遇到偶数年时,你将总和设置为 0。当它是奇数年时,你正在增加总和。 Whenever you set the sum to 0, it undoes any incrementing you did in the previous iterations of the loop.每当您将总和设置为 0 时,它都会撤消您在循环的先前迭代中所做的任何递增。 Try printing sum out at the end of every loop and see if it says what you think it should say.尝试在每个循环结束时打印 sum ,看看它是否说出了你认为应该说的内容。

else :
    sum = 0

This statement is resetting the value of sum back to zero.此语句将 sum 的值重置为零。 Hence you can simply discard it.因此,您可以简单地丢弃它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM