我有一个包含重复值的数组。我需要显示在数组中找到每个值的次数。
假设我有一个包含 8 个值的数组,array = {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);
}
}
}
提前致谢