我正在自己完成一本 o'reilly 教科书中的问题集,我对我应该用这个程序做什么感到有点困惑。
问题是:编写一个函数 count(number, array, length)
来计算 number 在 array
中出现的次数。该数组具有 length
元素。该函数应该是递归的。编写一个测试程序来配合该功能。
这个问题是逐字抄写的,但是我对这个问题有几个疑问。如果您可以发表评论,说明您对以下内容的看法,那就太好了:
- 好的,我需要一个长度为
length
的数组
,我可以在槽中存储我自己的数字吗?还是生成随机整数放入槽中? - 还有,我有正确的计划吗?我的计划是:
创建数组并在 main 中调用 count
。
函数 count
将是一个 if 循环,遍历数组直到它找到 number
然后它会将 1 添加到计数器。然后 count
函数将使用参数 count(int number; int array; int (length - 1))
现在我试图通过它说服自己,我现在更加困惑了。也许我只是让问题变得更难了。任何提示都会有所帮助。谢谢
最佳答案
我认为一个代码片段比一大堆文字更有值(value)。所以我会去做这样的事情:
#include <iostream>
int count(int num, int* arr, int length) {
if (!length)
return 0;
int c = count(num, arr+1, length-1);
return arr[0] == num? c + 1: c;
}
int main(void) {
int arr[10] = {1, 2, 3, 4, 3, 2, 1, 4, 3, 2};
std::cout << count(2, arr, 10);
return 0;
}
输出:
3
关于c++ - 编写一个函数 count(number, array, length) 来计算 number 在数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16825494/