见以下程序
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] a = Generate();
Print(a);
int max = Max(a);
int indexOfMax = IndexOfMax(a);
Console.WriteLine("Max={0}, Index={1}", max, indexOfMax);
int min = Min(a);
int indexOfMin = IndexOfMin(a);
Console.WriteLine("Min={0}, Index={1}", min, indexOfMin);
}
/// <summary>
/// 随机生成10个0到100之间的互不相同的整数
/// </summary>
/// <returns></returns>
static int[] Generate()
{
HashSet<int> s = new HashSet<int>();
Random rnd = new Random();
while (s.Count < 10)
{
s.Add(rnd.Next(0, 100));
}
return s.ToArray();
}
/// <summary>
/// 输出所有元素
/// </summary>
/// <param name="a"></param>
static void Print(int[] a)
{
foreach (int v in a)
{
Console.WriteLine(v);
}
}
/// <summary>
/// 并求出最大数
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
static int Max(int[] a)
{
int v = a[0];
for (int i = 1; i < a.Length; i++)
{
if (v < a[i]) v = a[i];
}
return v;
}
/// <summary>
/// 并求出最小数
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
static int Min(int[] a)
{
int v = a[0];
for (int i = 1; i < a.Length; i++)
{
if (v > a[i]) v = a[i];
}
return v;
}
/// <summary>
/// 最大数对应的数组元素下标
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
static int IndexOfMax(int[] a)
{
int v = a[0];
int index = 0;
for (int i = 1; i < a.Length; i++)
{
if (v < a[i])
{
v = a[i];
index = i;
}
}
return index;
}
/// <summary>
/// 最小数对应的数组元素下标
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
static int IndexOfMin(int[] a)
{
int v = a[0];
int index = 0;
for (int i = 1; i < a.Length; i++)
{
if (v > a[i])
{
v = a[i];
index = i;
}
}
return index;
}
}
}