How do I use the "Math.Max" method in C # without having to create a lot of variables?

0

I'm trying to solve an exercise that looks like this:

  

Make an algorithm that reads the height and enrollment of ten students. Show highest student enrollment and lowest student enrollment

And my code at the moment looks like this:

 Console.WriteLine("Altura dos Alunos");
        for ( int i = 0; i <= 10; i++)
        {
            Console.WriteLine("Qual a sua altura: ");
            double altura = Convert.ToDouble(Console.ReadLine ());
            Console.WriteLine("Qual sua matrícula? Ex: 1234");
            int matricula = Convert.ToInt32(Console.ReadLine());
            double altura2 = 0;
            Math.Max( altura, altura2 );
            altura2 = altura;
        }

How do I use the Math.Max() method to get the highest height and show it later without having to create 10 variables?

    
asked by anonymous 05.08.2018 / 03:34

1 answer

0

In fact this is very confusing. you must first declare the variable that will control the maximum height before entering the loop, it must be initialized with a value below that allowed.

Inside you will do the comparison and update the maximum height with the maximum between the previous and the entered. Note that I have done the conversion the right way so as not to give error when the typing is wrong. If typing does not pass the test, it returns 1 in the loop requiring a new typing of that element, waiting right now.

At the end of the loop, what about the control variable is the maximum height.

I gave a more meaningful name in the control variable. I took what was not relevant.

Want fewer variables than this? There's no way. You can delete the variable altura if you do not check if the typing is correct. You can give up i if you repeat the request 10 times instead of making a loop.

using static System.Console;
using static System.Math;

public class Program {
    public static void Main() {
        var maxAltura = -1.0;
        for (int i = 0; i < 10; i++) {
            WriteLine("Qual a sua altura: ");
            double altura;
            if (double.TryParse(ReadLine(), out altura) && altura > 0) maxAltura = Max(maxAltura, altura);
            else i--;
        }
        WriteLine(maxAltura);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
05.08.2018 / 03:54