首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

递归求解变慢,哪有错?求解答,该怎么处理

2013-07-16 
递归求解变慢,哪有错?求解答#include stdio.h#include stdlib.h#define NUL 0#ifndef NULL#define NUL

递归求解变慢,哪有错?求解答

#include <stdio.h>
#include <stdlib.h>
#define NUL 0
#ifndef NULL
#define NULL ((void *)0)
#endif
float static
square( int n )//递归求解
{
if( 1==n )
{
return 1;
}
else
{
return ( square(n-1)+n/square(n-1) )/2;
}
}
float static
square_for( int n )//for循环求解
{
int i=n,k;
float a=1;
if( i==1 )
{
return 1;
}
else
{
for( k=2;i>=k;k++ )
{
a=(a+k/a)/2;
}
return a;
}
}
void main(void)
{
#if ( 0 )
int n=1;
for(;n<100;n++)
{
float n_square;
n_square=square_for( n );
printf("%f\n",n_square);
}
#endif
int n=1;
for(;n<100;n++)
{
float n_square;
n_square=square( n );
printf("%f\n",n_square);
}
}
递归求解变慢,哪有错?求解答,该怎么处理
递归开平方到5.38开始很慢,使用for循环的函数则瞬间输出0-100得平方根。所求得值为近似,两种方法得到得值相同。
递归 Square? printf
[解决办法]

square( int n )//递归求解
{
    if( 1==n )
    {
        return 1;
    }
    else
    {
        float prev_value = square(n-1);
        return ( prev_value+n/prev_value )/2;
    }
}

[解决办法]
楼上正解。
在讲解递归时,很多教材会以 斐波那契 数列作例子
看来楼主没有好好学递归呢。

热点排行