2

我有一个问题,我想知道如何在 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...

如果有人可以帮助我,我会非常高兴!

4

2 回答 2

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 名。

于 2018-05-03T02:50:42.053 回答
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循环,以防他们输入小数以外的内容。

于 2018-05-03T03:04:32.723 回答