Problem with larger and smaller (while)

Asked

Viewed 303 times

0

Develop an algorithm that reads ten user-informed values and tells the highest and lowest read value.

cont = 0
n = 0
maior = n
menor = n
while cont < 3:
    n = int(input('Insira os números: >>> '))
    if n > maior :
        maior = n
    elif menor > n :
        menor = n
    cont = cont + 1
    print(menor,maior)
  • What’s the matter?

  • the code always works with the smallest = 0, I imagine it is on account of n = 0 in 2° line, but if I take the n from there the variable is as if it were not defined

1 answer

0


The problem is that you start the variables bigger and smaller as 0 (in this case you should start as the first value read to compare, since there can be negative values, less than 0) and the indentation of the print that shows the smallest and the largest that should show only at the end, the code would look like this:

cont = 0
while cont < 10:
    n = int(input('Insira os números: >>> '))
    if cont == 0 :
        menor=n
        maior=n
    if n > maior :
        maior = n
    elif menor > n :
        menor = n
    cont = cont + 1
print(menor,maior)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.