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

Asked

Viewed 296 times

0

I’m trying to solve an exercise that’s like this:

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

And my code right now is 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;
        }

Like I use the method Math.Max() to take the higher height and show it later without me having to create 10 variables?

  • first you need to have where to store the ten students...

  • Then I will have to create 10 variables even to store the height and then use Math.Max?

  • it is more likely that this is an exercise using arrays, so you only declare an array with 10 positions

1 answer

0


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

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

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

I gave a more meaningful name on the control variable. I took out what wasn’t relevant.

Want less variables than this? No way. It is possible to delete the variable altura to give up the check if the typing is right. It is possible to give up i 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);
    }
}

Behold working in the ideone. And in the .NET Fiddle. 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.