递归调和函数返回 NaN
我编写了以下示例代码来查找 N 的谐波值(1+1/2+1/3+...1/N)。阅读以粗体编写的代码中的注释,帮助我找出为什么会发生这种情况。
#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;
}
谢谢, 娜迦
I have written the following sample code to find the harmonic value of N. (1+1/2+1/3+...1/N). Read the comments in the code written in BOLD and help me to find why is this happening.
#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;
}
Thanks,
Naga
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你想做:
I think you want to do:
我的第一个想法是,你几乎不应该将浮点数与简单的相等进行比较,因此“if(n==0)”应该是“if(n<=EPSILON)”,“if(n==1)”应该是“if( n<= 1.0f + EPSILON)”,其中 EPSILON 是一个小的正分数,可能是 1.0e-5。取决于您可以依赖的精度。
但后来我意识到 n 应该是一个 int 。在除法之前将其投射到浮点数上。由于与“n”的比较表明您面临无限递归的风险。
考虑使用双精度数而不是浮点数。
Matthew Flaschen 的回答揭示了您收到 NaN 消息的真正原因。原始代码不会从“else”返回任何内容,因此调用者可能正在从堆栈中读取垃圾。因此,NaN。
My first thought was that you should almost never compare floats with simple equality so "if(n==0)" should be "if(n<=EPSILON)" and "if(n==1)" should be "if(n<= 1.0f + EPSILON)" where EPSILON is a small positive fraction, maybe 1.0e-5. Depends on how much precision you can depend on.
But then I realized that n should be an int. Cast it to a float before the division. As the comparisons with "n" stand you risk infinite recursion.
Consider using a double instead of a float.
Matthew Flaschen's answer gets to real reason you get the NaN message. The original code doesn't return anything from the "else" so the caller is probably reading garbage from the stack. Hence, the NaN.