我有一個包含重複值的數組。我需要顯示在數組中找到每個值的次數。如何顯示數組值在數組中的時間?
讓我們說,我有8個值的數組,數組= {1,2,3,1,1,2,6,7} 我需要的輸出爲:
1 was found 3 times
2 was found 2 times
3 was found 1 time
6 was found 1 time
7 was found 1 time
這裏是我的代碼。現在,我將數組中的每個值保存到一個變量中,然後遍歷數組以檢查值是否存在,然後將其打印出來。
int[] nums = { 2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32 };
for (int i = 0; i < nums.Length; i++)
{
int s = nums[i];
for (int j = 0; j < nums.Length; j++)
{
if (s == nums[j])
{
Console.WriteLine(s);
}
}
}
預先感謝
現在這就是我所說的真棒! – Aditi 2013-03-06 11:48:58
這將是很好的解釋OP你在這裏做什麼......不錯的答案然而。 – Th0rndike 2013-03-06 11:49:56
@ Th0rndike更好? – 2013-03-06 11:52:41