【发布时间】:2021-12-24 18:04:57
【问题描述】:
我在 Visual Studio 中用 C# 编写了一个控制台应用程序 (.NET 5.0),它将数组从高到低排序,然后它必须打印出该数组中的第二大元素。
我已经接近了,但我在过去 2 小时里一直在尝试,但我不明白为什么我总是在最后一个“if”中得到一个越界错误。该程序应该检测重复项,例如,如果输入是“1 1 2 2 5 5 9 9”,它将打印出“5”,因为它是第二大的。
我当前的代码在下面,我无法让它在不崩溃的情况下工作
使用系统;
namespace second_largest
{
class Program
{
static void Main(string[] args)
{
double[] input = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToDouble);
for (int repeat = 0; repeat < input.Length; repeat++)
{
for (int j = 0; j < input.Length - 1; j++)
{
if(input[j] < input[j+1])
{
double temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
}
}
}
for (int i = 0; i < input.Length; i++)
{
if(input[i] == input[i + 1])
{
}
else
{
Console.WriteLine(input[i]);
}
Console.WriteLine(input[i]);
}
}
}
}
【问题讨论】:
-
c-sharpcorner.com/code/3108/… 一个很好的例子
-
if(input[i] == input[i + 1])这里i + 1th 索引超出范围,因为您有for (int i = 0; i < input.Length; i++)循环