Define the lowest and highest value among three numbers

Asked

Viewed 109 times

-3

Print do formulário.Este é o enunciado do exercicioI’m trying to create a program in c# using windows Forms where it gets 3 numbers and tells me which is the biggest and which is the smallest, but I’m really very beginner and I don’t think where this error is, I already checked the list of errors of the IDE but this empty, it’s logic problem anyway. The code works but wrong.

Follow my code below:

        double n1 = 0;
        double n2 = 0;
        double n3 = 0;

        n1 = double.Parse(txtb1.Text);
        n2 = double.Parse(txtb2.Text);
        n3 = double.Parse(txtb3.Text);

        if (n1 > n2 && n1 > n3)
        {
            MessageBox.Show("O maior número é: " + n1);
        }

        else if (n1 > n2 && n1 < n3)
        {

        }

        else if (n1 < n2 && n1 < n3)
        {
            MessageBox.Show("O menor número é: " + n1);
        }

        else if (n2 > n1 && n2 > n3)
        {
            MessageBox.Show("O maior número é: " + n2);
        }

        else if (n2 > n1 && n2 < n3)
        {

        }

        else if (n2 < n1 && n2 < n3)
        {
            MessageBox.Show("O menor numero é: " + n2);
        }

        else if (n3 > n1 && n3 > n2)
        {
            MessageBox.Show("O maior número é: " + n3);
        }

        else if (n3 > n1 && n3 < n2)
        {

        }

        else if (n3 < n1 && n3 < n2)
        {
            MessageBox.Show("O menor numero é: " + n3);
        }
  • 1

    "works but in the wrong way", how would be a "wrong way" to work? What values did you report and what was the result? I also noticed that you are using the else if in all conditions, so remember that a else if is executed only if no previous condition is met. In your case it will only display one message at a time.

  • I put, for example, 1, 5, 10 respectively but he always accuses that the first number is the largest ( in case 1) and does not tell me which is the smallest

  • And if you put 5, 1, 10, it’s still the first number?

  • yes, always the first number (if you want to put form print)

  • Check that these variables are renamed correctly txtb1.Text, txtb2.Text, txtb2.Text.I tested with these values by placing directly on the variables n1, n2, n3 and worked for the values 1, 5, 10

  • It has a lot of if and Else nested and this can make it difficult to check. Have you tried debugging the code? https://docs.microsoft.com/pt-br/dotnet/core/tutorials/debugging-with-visual-studio#:~:text=Press%20F5%20for%20run%20o,Start%20Debugging%20from%20the%20menu.

  • @Bernardolopes yes, they are, (n1, N2 and N3 are variables) (txtb 1, 2 and 3 are the textbox that receive the values

  • @Gabrielsantana was worth it man I’ll take a look

  • Check the text box boxes

  • ?? but they have no influence on the code... are normal there.

  • but can for example is in form type NUMBER 1 and point to the variable txtb3

  • No, they’re all in order...

  • I suggest going in parts. First you try to show the largest and smallest without textbox (for example, with fixed values: n1 = 1; n2 = 5; n3 = 10;), because the way it is, you can’t tell if the problem is in reading the data or in its algorithm (or in a combination of both). Besides, the information you gave ("always accuses that the first number is the largest") does not proceed: see here a test with 1, 5 and 10 (informs that 1 is smaller) and here another with 5, 1 and 10 (does not print anything because it falls in one of else if emptiness)

  • In fact, so that one else if empty? If you do not want anything to be done in a certain condition, simply do not test that condition, that it is naturally ignored... That being said, if it’s only three numbers, you don’t need that lot of if/else, you can do it smarter: https://answall.com/a/460749/112052 (this is in Python, but it’s not hard to adapt the idea to C#: https://ideone.com/Ahbm63) (of course, in practice, to sort several numbers, it is better to use what is already ready in the language, as already suggested in the answers)

Show 9 more comments

4 answers

0

If I understand your problem from your comments is that your program only displays the largest or only the smallest and not both at the same time.

This is due to the fact that when using if with several else if only the first of them whose condition is true will be executed. In your case, more than one else if evaluates as true (one for the largest number and one for the smallest). A first alternative is to put everything as if since you’ve made all the possible combinations.

Another option is to use the library Math with the methods Maxand Min. Thus replacing your entire block if for:

MessageBox.Show("O maior número é: " + Math.Max(n1,Math.Max(n2,n3)));
MessageBox.Show("O menor numero é: " + Math.Min(n1,Math.Min(n2,n3)));

0

   double n1, n2, n3;

    n1 = double.Parse(txtb1.Text);
    n2 = double.Parse(txtb2.Text);
    n3 = double.Parse(txtb3.Text);

        if (n1 > n2 && n1 > n3)
        {
            MessageBox.Show("O maior número é: " + n1);
            if (n2 > n3) { MessageBox.Show("O menor número é: " + n3); } else { MessageBox.Show("O menor número é: " + n2); }

        }else
        {
            if (n2 > n1 && n2 > n3)
            {
                MessageBox.Show("O maior número é: " + n2);
                if (n1 > n3) { MessageBox.Show("O menor número é: " + n3); } else { MessageBox.Show("O menor número é: " + n1); }
            }

            else
            {                     
              MessageBox.Show("O maior número é: " + n3);
                if (n2 > n1) { MessageBox.Show("O menor número é: " + n1); } else { MessageBox.Show("O menor número é: " + n2); }
            }
        }

I did so because it is a small comparison between 3 numbers, if you have more numbers the recommended is to use the class Math with the methods Min and Max. Below I will leave the link to read the documentation about the class, if you are interested in knowing more. https://docs.microsoft.com/pt-br/dotnet/api/system.math?view=net-5.0

0

You can also use a list and sort it, but it is much slower depending on the case than compare with comparison operators.

// Declarando a lista
List<double> lista = new List<double>();

// Adicionando os valores à lista
lista.Add(double.Parse(txtb1.Text));
lista.Add(double.Parse(txtb2.Text));
lista.Add(double.Parse(txtb3.Text));

// Ordenando em ordem crescente
lista.Sort();

// Pegando o menor e o maior valor
double menor = lista[0]; // O primeiro da lista
double maior = lista[lista.Count - 1] // O último da lista

0

If I understand correctly, your program needs to display the lowest and highest value entered by the user. I believe a simple approach would be to create a vector (double[]) with the three numbers inserted and using the methods Min() and Max(), available on namespace System.Linq. The methods I mentioned are available for collections that implement the interface IEnumerable; return the lowest and highest value within a collection, respectively.

At the beginning of your file, enter the use of the mentioned namespace to access the methods:

using System.Linq;

So you can just call the method MessageBox.Show directly, without the need to check which number is larger/smaller or have to sort a list to do so, for example:

// criando um vetor de tamanho fixo, dado que precisa comparar apenas três números
double[] valoresInseridos = new double[3] { n1, n2, n3 };

MessageBox.Show($"Menor valor: {valoresInseridos.Min()}");
MessageBox.Show($"Maior valor: {valoresInseridos.Max()}");

Browser other questions tagged

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