给定数组通过递归传递最大数字的算法,但通过引用传递结果。
tam:数组的大小
首先我通过值实现了它,它对我有用,但我需要通过引用结果传递它,我真的不知道错误可能是什么,如果你可以指导我,因为在编译它时,我做了不返回任何内容
#include <stdio.h>
#include <stdlib.h>
void search(int a[], int tam, int max,int *result);
int main()
{
int max,tam=5, result;
int array[5]={3,1,5,8,6};
max=array[0];
search(array, tam, max, &result);
printf("the biggest number is: %d",result);
return 0;
}
void search(int a[], int tam, int max, int *result )
{
if(tam==1)
*result=max;
if(max<a[tam-1])
max=a[tam-1];
search(a,tam-1,max,result);
}
Blockquote
最佳答案
使用“clang -Wall”编译时,您会收到以下警告:
warning: all paths through this function will call itself [-Winfinite-recursion]
确实,您的函数中没有有效的基本情况和归纳步骤。
我建议转换为以下内容:
#define MAX(x, y) ((x) > (y)) ? x : y
int search(int a[], int tam )
{
// base case if last element
if (tam == 1) return a[0];
// inductive case (max of this and following elements)
return MAX(a[0], search(a + 1, tam - 1));
}
关于c - 如何在c中的递归算法中通过引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206880/