C++ Recursive Function

2011-12-20 8:18 am
Write the complete function f2() which uses a recursive approach to perform the function f1() does.

int f2 ( int a[], int size, int current, int key)
{
// Your code for the answer should be inserted here.
}

#include <iostream>
using namespace std;

int f1 ( int a[], int size, int key)
{
int count = 0;
for ( int i = 0 ; i < size ; i++ )
{
if ( a[i] < key )
{
cout << a[i] << "/";
count++;
}
}

return count;
}

int main()
{
int result;
int a[4] = {6,8,7,3};
result = f1(a,4,7);
cout << endl;
cout << result << endl;
}

回答 (1)

2011-12-20 12:37 pm
✔ 最佳答案
int f2 ( int a[], int size, int current, int key)
{
int count = 0;
if ( current < size )
{
if ( a[current] < key )
{
cout << a[i] << "/";
count = 1;
}
count += f2(a, size, ++current, key)
}
return count;
}

int main()
{
int result;
int a[4] = {6,8,7,3};
result = f2(a,4,0,7);
cout << endl;
cout << result << endl;
}


2011-12-20 04:38:48 補充:
correction:
cout << a[i] << "/";
should be
cout << a[current] << "/";


收錄日期: 2021-04-24 09:43:29
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20111220000051KK00007

檢視 Wayback Machine 備份