Why doesn’t my variable change the value?

Asked

Viewed 99 times

1

I have several variables and one of them is menor, when checking her out (output) I realized that the same always remains at zero, because this is occurring?

int z, menor = 0, maior = 0;

                for (int i = 1; i <= 5; i++)
                {
                    Console.WriteLine("informe o valor: ");
                    z = int.Parse(Console.ReadLine());

                    if (z <= menor)
                    {
                        menor = z;
                    }
                    else if (z >= maior)
                    {
                        maior = z;
                    }
                }
                Console.WriteLine("MAIOR: " + maior);
                Console.WriteLine("MENOR: " + menor);

                Console.ReadLine();
  • This depends on the range of values that can be informed at the entrance. Ideally, you should initialize the smallest variable with the highest possible value for that data type and for the largest variable the lowest possible value to be informed for the data type. Another possibility, which is independent of these maximum and minimum values for the data type, is that you assign the lower and higher variables the value read in the first reading and in the following readings to make the appropriate checks.

  • What exactly are you trying to do there?

2 answers

3


Because you’re starting him at 0, so he’s the smallest, he’ll only have a smaller one if he type negative, so he has to start with a bigger one, as long as possible (there’s another option but for this case it complicates logic), something like this:

using static System.Console;

public class Program {
    public static void Main() {
        int menor = int.MaxValue, maior = 0;
        for (int i = 0; i < 5; i++) {
            WriteLine("informe o valor: ");
            if (!int.TryParse(ReadLine(), out var valor)) WriteLine("valor inválido");
            if (valor <= menor) menor = valor;
            if (valor >= maior) maior = valor;
        }
        WriteLine("MAIOR: " + maior);
        WriteLine("MENOR: " + menor);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I took advantage and fixed other problems that the code had.

-2

Begins the variable minor with the entered value of the user and then compares to find the smallest

Browser other questions tagged

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