C#不反復輸入一個數組中一切元素的辦法。本站提示廣大學習愛好者:(C#不反復輸入一個數組中一切元素的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#不反復輸入一個數組中一切元素的辦法正文
本文實例講述了C#不反復輸入一個數組中一切元素的辦法。分享給年夜家供年夜家參考。詳細以下:
1.算法描寫
0)輸出正當性校驗
1)樹立暫時數組:與原數組元素一樣。該步調的目標是避免傳入的原數組被損壞
2)對暫時數組停止排序
3)統計暫時數組共有若干個分歧的數字。該步調的目標是為了肯定成果集數組的長度
4)樹立成果集數組,只寄存分歧的數字
5)前往成果集
2.函數代碼
/// <summary>
/// 樹立包括原數組內一切元素且元素間互不反復的新數組
/// </summary>
/// <param name="array">原數組</param>
/// <param name="isAsc">true:升序分列/false:降序分列</param>
/// <returns>新數組</returns>
private static int[] DifferentElements(int[] array, bool isAsc = true)
{
//0.輸出正當性校驗
if (array == null || array.Length == 0)
{
return new int[] { };
}
//1.暫時數組:與原數組元素一樣
int[] tempArray = new int[array.Length];
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = array[i];
}
//2.對暫時數組停止排序
int temp;
for (int i = 0; i < tempArray.Length; i++)
{
for (int j = i; j < tempArray.Length; j++)
{
if (isAsc)
{
if (tempArray[i] > tempArray[j])
{
temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
else
{
if (tempArray[i] < tempArray[j])
{
temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
}
//3.統計暫時數組共有若干個分歧的數字
int counter = 1;
for (int i = 1; i < tempArray.Length; i++)
{
if (tempArray[i] != tempArray[i - 1])
{
counter++;
}
}
//4.樹立成果集數組
int[] result = new int[counter];
int count = 0;
result[count] = tempArray[0];
for (int i = 1; i < tempArray.Length; i++)
{
if (tempArray[i] != tempArray[i - 1])
{
count++;
result[count] = tempArray[i];
}
}
//5.前往成果集
return result;
}
3.Main函數挪用
static void Main(string[] args)
{
int[] array = new int[]
{
1, 9, 1, 9, 7, 2, 2, 5, 3, 4,
5, 6, 3, 3, 6, 2, 6, 7, 8, 0
};
//數組:包括原數組內全體元素且不反復(升序分列)
int[] result1 = DifferentElements(array);
foreach (int i in result1)
{
Console.Write(i.ToString() + "\t");
}
//數組:包括原數組內全體元素且不反復(降序分列)
int[] result2 = DifferentElements(array,false);
foreach (int i in result2)
{
Console.Write(i.ToString() + "\t");
}
Console.ReadLine();
}
4.法式輸入示例

願望本文所述對年夜家的C#法式設計有所贊助。