Nag*_*aga 3 c tail-recursion nan
我写了下面的示例代码来找到N的谐波值(1 + 1/2 + 1/3 + ... 1/N).阅读用BOLD编写的代码中的注释,并帮助我找到为什么会发生这种情况.
#include <stdio.h>
float harmonic(float n, float har) {
if(n==0) {
return 0;
}
if(n==1) {
printf("%f\n", har+1.0f);***/* This prints value 1.5000*/***
return har+1.0f;
}else{
harmonic(n-1, (har+(1/n)));
}
}
int main()
{
printf("%f\n", harmonic(2, 0.0f)); **/* But this prints value nan(Not a Number)*/**
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢,娜迦