私の配列の中で2番目に大きい番号を見つけることに問題があります。それは、すべての私の例では機能しません。 私はキーボードから数値を読み込んだ後、メソッドをテストに入れ、次にソートします。例:(ユーザーが入力した)1,2,3,4,5,6,7,8,9,10 exit:10,9、.. 3,2,1 今度は、forループで2番目に大きい番号を表示したい。 **タスクは次のとおりです。可能であればCW( "エラー") **配列の2番目の最大値を見つける
in codeコメント//ここでコードの一部を正しい方法で書く方法がわかりません。
私は私の問題は、理にかなって願ってい...
public static int test(int[] polje)
{
int temp = 0;
Console.WriteLine();
for (int c = 0; c < polje.Length; c++)
{
for (int b = c + 1; b < polje.Length; b++)
{
if (polje[c] > polje[b])
{
temp = polje[c];
polje[c] = polje[b];
polje[b] = temp;
}
}
}
int secondlargest = 0;
//HERE
for (int i = polje.Length - 1; i >= 0; i--)
{
if (polje[polje.Length - 2] == polje[polje.Length - 1] || polje[polje.Length - 2] == 0)
{
Console.WriteLine("Wrong!");
break;
}
else
{
Console.WriteLine("Second largest number is :{0}", polje[polje.Length - 2]);
secondlargest = polje[polje.Length - 2];
break;
}
}
return secondlargest;
}
static void Main(string[] args)
{
int[] polje = new int[10];
Console.WriteLine("Enter values");
for (int i = 0; i < 10; i = i + 1)
{
polje[i] = int.Parse(Console.ReadLine());
if (polje[i] == 0)
{
break;
}
}
test(polje);
Console.ReadLine();
}
}
}
この宿題はありますか?リストと並べ替え、またはLINQとOrderByDescendingとTake(2)を使用して2つの最大値を取得するためです。 –
既にソートしている場合は、2番目のforループのポイントは何ですか?昇順または降順の並べ替えによって、配列に2つ以上のレコードがある限り、配列の2番目のインデックスまたは2番目の最後のインデックスを選択できます。 – RizJa
http://stackoverflow.com/questions/14810444/find-the-second-maximum-number-in-an-array-with-the-smallest-complexity – Damith