åè代ç å¦ä¸ï¼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FindMaxWithIndex
{
/// <summary>
/// æä¸ä¸ªæ°ç»ï¼æ¯ä¸ªå
ç´ çå¼é½æ¯å®æ°ï¼è¯·ååºæ±æ大å
ç´ çå¼åå
¶ä½ç½®çç®æ³
/// </summary>
class Program
{
static void Main(string[] args)
{
double[] Num = new[] { -8, 4543.9, 4543.9, 3, 45, 654.7, 7, 66, 35, 45, 4, 6, 4543.9, 5, 46, 54, 6, 43, 5.980, 34, 4543.9 };
//double[] Num = new [] { 1.0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int[] index = SearchMaxWithIndex(Num);
Console.WriteLine("The max number is: {0}", Num[index[0]]);
Console.Write("The index of max number is:");
for (int i = 0; i < index.Length; i++)
{
if (index[i] == -1) break;
Console.Write(" '{0}'", index[i]);
}
Console.ReadKey();
}
private static int[] SearchMaxWithIndex(double[] arr)
{
int[] pos = new int[arr.Length]; //è®°å½æ大å¼æå¨ä½ç½®çæ°ç»
int position = 0; //åå§è®¾å®æ°ç»ç第1个å
ç´ ä¸ºæ大å¼
int j = 1;//jæ示ä½ç½®æ°ç»posçä¸æ
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > arr[position])
{
position = i; //è®°ä¸æ°çæ大å¼çä½ç½®
j = 1; //ä½ç½®æ°ç»posçä¸æ æ¢å¤ä¸º1ï¼ä¸æ 为0çä½ç½®ä¸ºpositioné¢ç
}
else if (arr[i] == arr[position])
pos[j++] = i; //è®°ä¸éå¤æ大å¼çä½ç½®
}
pos[0] = position; //ä½ç½®æ°ç»posçä¸æ 为0çä½ç½®ä¸ºpositioné¢ç
if (j < arr.Length) pos[j] = -1; //-1为æ è¯å¼ï¼è¡¨ç¤ºä½ç½®æ°ç»posä¸æ 为0, 1, 2â¦(j-1)çä½ç½®åæ¾çæ¯æ大å¼æå¨çä½ç½®
return pos;
}
}
}
温馨提示:答案为网友推荐,仅供参考