递归和非递归实现规律函数
1、问题
A(n) = n / (2 * n + 1)
B1 = 2 + A1;
B2 = 2 + A1 * (2 + A2);
B3 = 2 + A1 * (2 + A2 * (2 + A3));
....以此类推,求B(n)
B1 = 2 + A1;
B2 = 2 + A1 * (2 + A2);
B3 = 2 + A1 * (2 + A2 * (2 + A3));
....以此类推,求B(n)
2、代码实现
#include <stdio.h>
/**
A(n) = n / (2 * n + 1)
B1 = 2 + A1;
B2 = 2 + A1 * (2 + A2);
B3 = 2 + A1 * (2 + A2 * (2 + A3));
....以此类推,求B()
**/
float A(float n)
{
if (n < 0)
return 0;
float result = n / (2 * n + 1);
return result;
}
//非递归实现
float B(float n)
{
if (n < 0)
return 0;
float sum = 1;
for (int i = n; i >= 1; --i)
{
sum = sum * A(i) + 2;
}
return sum;
}
//递归实现
float recursion_B(float n)
{
if (n < 0)
return 0;
static float sum = 1;
if (n == 0)
return sum;
else
{
sum = sum * A(n) + 2;
recursion_B(n - 1);
}
}
int main()
{
for (int i = 0; i < 20; i++)
printf("B(%d) is %f\n", i, B(i));
printf("recursion_B(10) is %f\n", recursion_B(10));
}
3、运行结果
B(0) is 1.000000
B(1) is 2.333333
B(2) is 2.800000
B(3) is 2.990476
B(4) is 3.073016
B(5) is 3.109957
B(6) is 3.126829
B(7) is 3.134643
B(8) is 3.138300
B(9) is 3.140024
B(10) is 3.140842
B(11) is 3.141232
B(12) is 3.141419
B(13) is 3.141509
B(14) is 3.141552
B(15) is 3.141573
B(16) is 3.141583
B(17) is 3.141588
B(18) is 3.141591
B(19) is 3.141592
recursion_B(10) is 3.140842
赞 (0)