要求用户输入一系列数字,然后显示最大值和最小值的程序

2024-04-26 23:53:59 发布

您现在位置:Python中文网/ 问答频道 /正文

Design a program with a loop that lets the user enter a series of numbers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.

The user can enter any number of input value: negative, 0, or positive. No arrays can be used. Also 2 modules have to be used to display a welcome message with a program description and display the largest and smallest numbers

我的循环似乎不能正常工作,因为不管我是否输入-99,它只能工作两次。它还接受首先输入的任何数字,并将其显示为最大和最小的数字

def main():

    #call the welcome module
    displayWelcome()

    #declare the local variables
    smallest = int()
    largest = int()

    #prompt user for the first number
    inputNum = int(input('Enter the first number (0 indicates end of input): '))

    #initialize largest and smallest to user input
    smallest = inputNum
    largest = inputNum

    #loop while sentinel has not been entered

    while inputNum != -99:

        #compare number input with largest and smallest
        if inputNum < smallest:
            smallest = inputNum
        elif inputNum > largest:
            largest = inputNum

        #prompt user for another number
        inputNum = int(input('Enter another number (0 indicates end of input): '))

         #call module to display the numbers
        displayLargestSmallest(largest, smallest)

def displayWelcome():

    #display welcome message and program descr
    print('Hello!')
    print('This program displays the largest and')
    print('smallest values of all input integers.')
    print('-99 indicates end of input')



def displayLargestSmallest(largestInput, smallestInput):

    #module to display numbers input
    print('The largest number input is ',largestInput)
    print('The smallest number input is ', smallestInput)

Tags: andofthetonumberinputdisplayprogram
1条回答
网友
1楼 · 发布于 2024-04-26 23:53:59

小的改进建议:

  • 您没有最大或最小限制,因此应该在开始时使用None
  • 使用while True:break,这样就不必写input()两次

代码:

def main():
    displayWelcome()

    smallest = None
    largest = None

    while True:
        #prompt user
        inputNum = int(input('Enter number (-99 indicates end of input): '))
        if inputNum == -99:
            # exit loop
            break

        #compare number input with largest and smallest
        if smallest is None or inputNum < smallest:
            smallest = inputNum
        if largest is None or inputNum > largest:
            largest = inputNum

        displayLargestSmallest(largest, smallest)

    # display again at the end
    displayLargestSmallest(largest, smallest)

相关问题 更多 >