【发布时间】:2015-10-20 08:16:11
【问题描述】:
我很难进行这样的练习:
编写一个程序,计算数组中每个不同数字的出现次数。整数是 0 - 9 之间的数字。以这个数组为例:
int numbers[] = {1, 5, 4, 7, 1, 4, 1, 7, 5, 5, 3, 1};
创建一个指向数组第一个元素的指针。循环遍历数组并计算指向数字的出现次数。数完数字 1 的出现次数后,指针会指向数字 5。计算 5 的出现次数,以此类推。在您循环了几次并且指针再次指向 1(数组的元素 4)之后,程序可能不会再数 1,因此您需要将分数保持在您已经数过的数字的某个位置。 em>
输出应该类似于:
1的出现次数为:4
3的出现次数为:1
4的出现次数为:2
5的出现次数为:3
7的出现次数为:2
我现在的代码计算了每个元素的外观:
int main()
{
int getallen[] = {1, 5, 4, 7, 1, 4, 1, 7, 5, 5, 3, 1};
int i , j, *aimedNumber, appearance = 0, arraySize = sizeof(getallen) / sizeof(int);
for(i=0;i<arraySize;i++)
{
aimedNumber = getallen[i]; // every loop, the pointer points to the next element
for(j=0; j<arraySize; j++) // loops through the array comparing the pointer
{
if(getallen[j]==aimedNumber) // if the element of the array == pointer
{
appearance++; // +1 to the appearance
}
}
printf("the appearance of %i in the array is: %i\n", aimedNumber, appearance);
appearance = 0; // after checking the appearance of the pointed number...
} // reset the appearance variable
return 0;
}
但我仍然需要检查我是否已经数过一个数字,如果我已经数过了,请确保该数字不会再次被计算。
提前致谢!
【问题讨论】:
-
如果你可以使用set,那么你的问题就解决了,但它是stl和c++
-
你的外循环应该运行在所有可能的数字上,即在你的情况下从 0 到 9,并且
aimedNumber等于 ´i`。 (当然,如果你知道可能值的范围,你可以只遍历内部循环一次,并为每个从 0 到 9 的数字填充一个计数数组。) -
好吧,您并没有在每次传递中减少数组中的数字,而是从 0 开始 j 。如果您数 1,请确保您的下一个数组从 5、4、7、4 开始...