我在一本 C++ 书中找到了一个练习,上面写着“编写一个函数来计算一个数字在数组中出现的次数。”。一切都很好,程序正在运行。但练习也表明该函数应该是递归的。
如何使递归函数像这样工作?
#include <iostream>
int count(int number, int array[], int length)
{
int counter = 0;
for(int i = 0; i < length; i++)
if(array[i] == number)
counter++;
return counter;
}
int main()
{
int numbers[10] = {3,4,1,2,4,5,6,5,4,5};
int number_to_search = 5;
std::cout << number_to_search << " appears "
<< count(number_to_search, numbers, 10)
<< " times in the array.";
return 0;
}