2

I have a question, I want to know how i can show on CONSOLE the 2 highest of N entered numbers? Im doing something like this:

Console.WriteLine("Enter the weight of the fish:");
if(decimal.TryParse(Console.ReadLine(), out _fishWeight))
{
    if (_fishWeight > _highest2)
    {
        _highest = _fishWeight;
        if (_fishWeight < _highest1)
        {
            _highest = _fishWeight;
        }
    }       
} 

but it doesn't work. It only shows me the _highest1 but not the other _highest...

If someone can help me, I would be really glad!

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Nikssj_
  • 187
  • 2
  • 3
  • 11
  • You're setting `_highest` but comparing to `_highest2` and `_highest1` and the second one is doing less than, are those typos? In any case you'll want to compare to whatever variable has the highest first and if it's higher set the second highest to the highest then the highest to the current value. Then if it's not higher than the highest you compare to the second highest and set it accordingly. – juharr May 03 '18 at 02:34
  • Add them all to a List, sort it, display the first two numbers. – Ron Beyer May 03 '18 at 02:40
  • Next time use [step by step debugging](https://learn.microsoft.com/en-us/visualstudio/debugger/getting-started-with-the-debugger) to check your code. – Martheen May 03 '18 at 02:51

2 Answers2

2

you want something more like

if (_fishweight > _highest)
{
    _highest2 = _highest;
    _highest = _fishweight;
}
else if(_fishweight > _highest2)
{
    _highest2 = _fishweight;
}

Alternatively If you want a more flexible leaderboard

// declare something like...

    private List<int> _leaderboard = new List<int>();
    private readonly int _leaderboardCount = 2;

// then update it like...    
    _leaderboard.Add(_fishweight);
    _leaderboard = _leaderboard.OrderByDescending(v => v).Take(_leaderboardCount).ToList();

Now you have the top 2, but you can easily change it to a top 10 later on if you want.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

Math.Max() is your friend here. No need to do manual comparison, just feed in two values, it'll output the highest of them and just set that to your _heighestWeight.

while (true)
{
    Console.Write("Enter the weight of the fish: ");
    var input = Console.ReadLine();
    if (decimal.TryParse(input, out _fishWeight))
    {
        break;
    }

    Console.WriteLine("Please only enter a decimal number");
    Console.Clear();
}

_heighestWeight = Math.Max(_fishWeight, _heighestWeight);

I also added a while loop in case they input something other than a decimal.

gilliduck
  • 2,762
  • 2
  • 16
  • 32