gpt4 book ai didi

c - 在 C 中搜索数组

转载 作者:行者123 更新时间:2023-11-30 15:16:05 25 4
gpt4 key购买 nike

我在进行如下练习时遇到了困难:

Write a program that counts the amount of appearances of every different number in an array. The integers are numbers between 0 - 9. Take this array as an example:

int numbers[] = {1, 5, 4, 7, 1, 4, 1, 7, 5, 5, 3, 1};

create a pointer that points to the first element of the array. Loop through the array and count the amount of appearances of the pointed number. After you've counted the amount of appearances of the number 1, the pointer will point to the number 5. count the amount of appearances of 5 and so on. After you've looped a couple of times and the pointer points to 1 again (element 4 of the array) the program may not count 1 again, so you need to keep the score somewhere of the numbers you've already counted.

The output should look something like:

The amount of appearances of 1 is: 4

The amount of appearances of 3 is: 1

The amount of appearances of 4 is: 2

The amount of appearances of 5 is: 3

The amount of appearances of 7 is: 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;
}

但我仍然需要有一些东西来检查我是否已经计算过一个数字,如果我计算过,请确保该数字不会再次计算。

提前致谢!

最佳答案

你有一个限制,数组中的数字只能在 0 和 9 之间(包括 0 和 9),这实际上使它变得更简单,因为这样你就可以有一个包含 10 个整数的“计数器”数组(每个整数一个)您“搜索”的数组中的数字),并且对于主数组中的每个数字,您增加计数器数组中相应的值(使用数字作为索引)。然后简单地打印出计数器数组中非零的值。

类似下面的内容

int count[10] = { 0 };  // Initialize all to zero

for (i = 0; i < arraySize; ++i)
++count[getallen[i]];

// Now print out all non-zero values from count,
// and the index is the number in getallen

关于c - 在 C 中搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com