打印最大的奇数

时间:2019-10-07 21:27:56

标签: python

对于这个问题,我想尝试打印最大的奇数,直到用户输入0。但是,当我尝试测试我的代码时,为什么我的代码返回3,而5应该是最大的奇数呢?返回。谁能帮我解决这个问题吗?

这是我的测试用例:

biggestOdd()

Enter a positive integer: 5
Enter a positive integer: 4
Enter a positive integer: 3
Enter a positive integer: 2
Enter a positive integer: 0
3


def biggestOdd():
biggest_odd_num = None
n = int(input("Enter a positive integer: "))
while n != 0:
    n = int(input("Enter a positive integer: "))
    if (n % 2 != 0 and (biggest_odd_num is None or n > biggest_odd_num)):
        biggest_odd_num = n
if biggest_odd_num:
    return biggest_odd_num
else:
    return 0

1 个答案:

答案 0 :(得分:1)

从不使用第一个输入n

def biggestOdd():
    biggest_odd_num = 0
    while True:
        n = int(input("Enter a positive integer: "))
        if not n:
            break
        if n % 2 != 0 and n > biggest_odd_num:
            biggest_odd_num = n
    return biggest_odd_num