第一個陣列是隨機填充的,它的長度是從控制臺設定的。我有一個陣列,我需要在其中撰寫一個重復數字的子陣列和重復數字的數量。例如 {3 3 3 3 3 4},3 3 3 3 是重復的數字,4 是它們的數字。
問題是如果陣列末尾有重復的數字,回圈不會輸出它們,如果我進入除錯模式,我可以看到并非所有數字都被寫入。可能是什么問題呢?
for (int i = 1; i < array.Length; i )
{
if (array[i - 1] == array[i])
{
if((i 1) != array.Length)
{
duplicateCount ;
addArray = array[i - 1];
duplicate = addArray " ";
}
else
{
duplicateCount ;
lastElement = array[i - 1];
duplicate = lastElement;
}
}
else
{
if (duplicateCount != 1)
{
addPrevious = array[i - 1];
duplicate = addPrevious " ";
duplicateArrays.Add(duplicate duplicateCount);
duplicate = "";
duplicateCount = 1;
}
else
{
duplicateCount = 1;
}
}
}
duplicateArrays.Add(duplicate duplicateCount);
uj5u.com熱心網友回復:
雖然 Antidisestablishmentarianism 代碼是最短的代碼,但它使用“ ^ ”,它是C# 8.0 中引入的結束運算子的索引。我并不在乎這一點,但這是一個值得了解的差異。在舊版本中編譯相同的代碼將生成編譯時例外。我將給出一個很長但對初學者友好的代碼,如果你讀兩遍它是不言自明的。
static void Main(string[] args)
{
int[] RandomArray = new int[] { 1, 2, 2, 3, 4, 4, 3, 1, 5, 2, 9, 8, 9, 8, 8, 5, 3, 4, 1 };
int RandomArrayLength = RandomArray.Length;
List<int[]> SubArrayList = new List<int[]>();
List<int> visited = new List<int>();
for (int i = 0; i < RandomArrayLength; i )
{
int elem = RandomArray[i];
if (!visited.Contains(elem))
{
visited.Add(elem);
List<int> templist = new List<int>();
for (int j = 0; j < RandomArrayLength; j )
{
if (elem == RandomArray[j])
{
templist.Add(elem);
}
}
if (templist.Count > 1) //You can remove this condition if you want to include all the elements
{
int elemCount = templist.Count;
List<int> sublist = new List<int>();
sublist.AddRange(templist);
sublist.Add(elemCount);
SubArrayList.Add(sublist.ToArray());
}
}
else
{
continue;
}
}
int SubArrayListCount = SubArrayList.Count;
for (int i = 0; i < SubArrayListCount; i )
{
int[] SubArr = SubArrList[i];
int SubArrCount = SubArr.Length;
for (int j = 0; j < SubArrCount; j )
{
Console.Write(SubArr[j].ToString() " ");
}
Console.WriteLine();
}
}

uj5u.com熱心網友回復:
替換初始化的陣列,因為聽起來您已正確填充陣列:
static void Main()
{
int[] array = new int[] { 9, 9, 9, 8, 7, 6, 6, 6, 6 };
List<int[]> subarrays = new();
for (int x = 0; x < array.Length; x )
{
int temp = x;
while (x < array.Length - 1 && array[x] == array[x 1])
x ;
if (x > temp)
{
int[] temparray = Enumerable.Repeat(array[temp], x - temp 2).ToArray();
temparray[^1] = x - temp 1;
subarrays.Add(temparray);
}
}
foreach (int[] item in subarrays)
Console.WriteLine(string.Join(" ", item));
}
輸出:
9 9 9 3
6 6 6 6 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347911.html
上一篇:無法在C 中使用setw獲得右對齊的數字三角形模式給空間
下一篇:從范圍中間開始并回圈的For回圈
