How to improve this method that compares three numbers?

Asked

Viewed 55 times

1

Can help me improve this little code so it’s less extensive and clean?

The code compares three numbers and shows which and the largest among them:

@IBAction func comprar(_ sender: Any) {

    if pNumero.text! > sNumero.text! {
        messageLabel.text = "Primeiro número e maior"
    }

    else if pNumero.text! < sNumero.text! {
        messageLabel.text = "Segundo número e maior"
    }

    if tNumero.text! > pNumero.text!{
        messageLabel.text = "o Terceiro número e maior"
    }


    else if tNumero.text! < sNumero.text! {
        messageLabel.text = "o Terceiro número e maior"
    }

    else if pNumero.text! == sNumero.text!{
        messageLabel.text = "Os dois números são iguais"

    }

1 answer

5


I’ve never used Swift in my life, but I’ll risk an answer.

@IBAction func comprar(_ sender: Any) {

    var maior = pNumero.text!

    messageLabel.text = "Primeiro número e maior"

    if sNumero.text! > maior {
        maior = sNumero.text!
        messageLabel.text = "Segundo número e maior"
    }

    if tNumero.text! > maior {
        maior = tNumero.text!
        messageLabel.text = "Terceiro número e maior"
    }

}

Explanation

You always store the highest value in a variable and compare the others to this value. If the new value is higher, update the variable. In the beginning, the first number is considered to be the largest, as there is no value to compare it. We check if the second value is greater than the first. If yes, maior takes on the value of sNumero, otherwise retains the value of pNumero. Then we check whether the third number is greater than maior. If yes, we update the value of maior with the value of tNumero, if no, keeps the current value.

A variation of this code, with the same logic, can be seen in operation here.

  • Ai Anderson, thanks for the help. The idea is, the user will enter 3 numbers and the if and Else analyze which is the largest number of the three. * Now I think of a condition that says which is the highest number and best of the three inserted

  • Best of three?

  • Greater number of the three

  • https://repl.it/F50n/0, see here working.

  • Worked perfectly!

  • Mark the answer as valid, if possible.

  • Done !!!!!!!!!!

Show 2 more comments

Browser other questions tagged

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