显示两个最高的N个数字c#

时间:2018-05-03 02:23:36

标签: c# console numbers highest

我有一个问题,我想知道如何在CONSOLE上显示N个输入数字中最高的2个?我做这样的事情:

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;
        }
    }       
} 

但它不起作用。它只显示_highest1而不是其他_highest ......

如果有人可以帮助我,我会很高兴的!

2 个答案:

答案 0 :(得分:2)

你想要更像

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

或者如果您想要更灵活的排行榜

// 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();

现在你有前2名,但如果你愿意,可以稍后将其轻松改为前10名。

答案 1 :(得分:0)

Math.Max()是你的朋友。无需进行手动比较,只需输入两个值,它会输出最高值,只需将其设置为_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);

我还添加了一个while循环,以防它们输入小数以外的其他内容。