简体   繁体   English

用尾递归计算谐波级数?

[英]TAIL recursion to calculate Harmonic Series?

I'm trying to calculate the Harmonic Series with TAIL recrusion,simple recrusion works but not the terminal version , This is the simple recrusion version :我正在尝试使用 TAIL 递归计算谐波级数,简单的递归有效但不是终端版本,这是简单的递归版本:

#include<stdio.h>
float calcul(int n)
{if(n==1)
return 1;
else
return (1/float(n)+(calcul(n-1)));
}
main()
{int i,n;float h,t;
t=1;
printf("type in a number :\n");
scanf("%d",&n);
printf("H(%d)= %.3f",n,calcul(n));}

this is TAIL recrusion but it doesn't work :这是 TAIL recrusion,但它不起作用:

#include<stdio.h>
float calcul(int n,float t)
{if(n<2)
return 1;
else
return calcul(n-1,t+(float(1)/float(n)));
}
main()
{int n;
float t;
t=1.00;
printf("type in a number :\n");
scanf("%d",&n);
printf("H(%d)= %.3f",n,calcul(n,t));}

I'm using c please help me :)我正在使用 c 请帮助我:)

The key point of tail recursion is that you all recursive calls are in tail position, which is not the case for you (you still have to do + after the recursive call).尾递归的关键是你所有的递归调用都在尾位置,这对你来说不是这样的(你在递归调用之后还是要做+)。

Fix that by introducing an accumulator that you return in the base case or update in the recursive case:通过引入一个在基本情况下返回或在递归情况下更新的累加器来解决这个问题:

float calcul(int n) {
    return calcul(n, 1);
}

float calcul(int n, float acc) {
    if (n == 1)
        return acc;
    else
        return calcul(n-1, acc + 1 / float(n));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM