您好,我有以下代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define min(x, y)(x < y)?(x):(y)
#define SIZE 1000
int valormenor(int a[], int n)
{
if(n == 1)
return a[0];
else
return min(a[0], valormenor(a + 1, n - 1));
}
int main(void)
{
int arr[SIZE] = {0}, i;
srand (time (NULL));
for(i = 0; i < SIZE; i++)
arr[i] = rand() % SIZE;
arr[5] = -1;
printf("%d\n", valormenor(arr, SIZE));
return 0;
}
重点是不明白,因为找最小数的时间太长了,我的理论是这个递归函数实现的不好,你说的是谁?
最佳答案
让我们在这里扩展 min
宏:
return min(a[0], valormenor(a + 1, n - 1));
变成了
return (a[0] < valormenor(a + 1, n - 1))?(a[0]):(valormenor(a + 1, n - 1));
如您所见,valormenor
被调用了两次。这两个递归调用进行了四次递归调用,这进行了八次递归调用,依此类推。这是一个经典的双重评估错误。
不要使用这样的宏。他们只是不值得头疼。
关于c - 执行算法递归求小数,速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760282/