這正常工作與我:
#include <stdio.h>
#include <string.h>
// define a struct that contains the (max, freq) information
struct arrInfo
{
int max;
int count;
};
struct arrInfo maxArr(int * arr, int max, int size, int count)
{
int maxF;
struct arrInfo myArr;
if(size == 0) // to return from recursion we check the size left
{
myArr.max = max; // prepare the struct to output
myArr.count = count;
return(myArr);
}
if(*arr > max) // new maximum found
{
maxF = *arr; // update the max
count = 1; // initialize the frequency
}
else if (*arr == max) // same max encountered another time
{
maxF = max; // keep track of same max
count ++; // increase frequency
}
else // nothing changes
maxF = max; // keep track of max
arr++; // move the pointer to next element
size --; // decrease size by 1
return(maxArr(arr, maxF, size, count)); // recursion
}
int main()
{
struct arrInfo info; // return of the recursive function
// define an array
int arr[] = {8, 4, 8, 3, 7};
info = maxArr(arr, 0, 5, 1); // call with max=0 size=5 freq=1
printf("max = %d count = %d\n", info.max, info.count);
return 0;
}
運行時,它輸出:
max = 8 count = 3
注意
在我的代碼示例中,我假定的數字爲正(初始化max
到0
),我不知道你的要求,但你可以詳細說明。
你的想法是什麼?你將如何使用遞歸來處理這些關於數組的信息? – abiessu 2014-09-30 22:37:13
要有效地使用遞歸,首先需要建立一個基本案例,一旦解決了整個問題,就可以避免遞歸。其次,你必須找到一些規則,使你從第一次遞歸函數調用到解決問題的進度。第三,通過遞歸調用函數來結合進度,直到第一步到達基本情況。 – JGroven 2014-09-30 23:33:10
將其分解爲兩部分。首先編寫一個遞歸函數來查找最大值。然後添加一種方法來跟蹤它發生的次數。 – molbdnilo 2014-09-30 23:46:06