What is the problem with this code that takes the highest and lowest value?

Asked

Viewed 783 times

2

I want to display the sum of the numbers typed as well as the largest and smallest number typed, only with while, if and else:

contador = 1
maior = 0
menor = 0
S = 0  # 1º NÚMERO A SER SOMADO

while contador <= 5:
    num = int(input("Digite o " + str(contador) + "º valor:"))
    if num >= maior:
        maior = num
    if maior < num:
        menor = num
    S += num
    contador += 1
print("A soma de todos os valore é igual a", S)
print("O maior valor digitado foi", maior)
print("O menor valor digitado foi", menor)

The program shows the sum and the highest value, but does not show the lowest value.

  • 1

    Did you debug the code? Did you test with chosen numbers and track what each line of your code does? I would say that the main problem of your code can be divided into two parts: 1) you test maior with num to define menor (should test menor); 2) the value of menor already starts very low (equal to 0). Unless your input contains negative numbers, it will never have a lower value than this. Programming requires "experiment" with logic. If you don’t do this, you will hardly learn correctly.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

You have two problems. You need to initialize the smallest number with a number that is the largest number to ensure that it will not be caught unless the smallest number typed is itself. This can be done with sys.maxsize. There are also two errors in the minor’s verification condition maior < num: needs to compare with the smallest and not the largest, and needs to check whether the num is less than menor, not unlike.

import sys

contador = 1
maior = 0
menor = sys.maxsize
S = 0
while contador <= 5:
    num = int(input("Digite o " + str(contador) + "º valor:"))
    if num > maior:
        maior = num
    if num < menor:
        menor = num
    S += num
    contador += 1
print("A soma de todos os valore é igual a", S)
print("O maior valor digitado foi", maior)
print("O menor valor digitado foi", menor)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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