递归和非递归实现规律函数
【摘要】 1、问题
A(n) = n / (2 * n + 1)
B1 = 2 + A1;
B2 = 2 + A1 * (2 + A2);
B3 = 2 + A1 * (2 + A2 * (2 + A3));
....以此类推,求B(n)
2、代码实现
#include <stdio.h> /** A(n)...
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
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/78808321
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)