递归嵌套的自由基C++
我正在尝试为sqrt(1+sqrt(2+sqrt(3+...))的第一个n项编写一个函数)
在C ++中。约束是该函数必须是递归的,并将n(巢的深度)作为唯一的参数。我不需要返回表达式本身,正是它评估的内容。例如:
n=1 -> sqrt(1) # which evaluates to 1
n=2 -> sqrt(1+sqrt(2)) # which evaluates to 1.55377
n=3 -> sqrt(1+sqrt(2+sqrt(3))) # which evaluates to 1.7122
我尝试过:
float nestedRadical(float n){
if (n==1){
return sqrt(1);
}else{
return sqrt(n + nestedRadical(n-1));
}
}
此代码导致1
是最深层的自由基,当它应该是最高的时候。我应该如何解决这个问题?
I'm trying to write a function for the first n terms of sqrt(1+sqrt(2+sqrt(3+...)))
in C++. The constraint is that the function must be recursive and take n (the depth of the nest) as the only parameter. I do not need to return the expression itself, just what it evaluates to. For example:
n=1 -> sqrt(1) # which evaluates to 1
n=2 -> sqrt(1+sqrt(2)) # which evaluates to 1.55377
n=3 -> sqrt(1+sqrt(2+sqrt(3))) # which evaluates to 1.7122
I've tried:
float nestedRadical(float n){
if (n==1){
return sqrt(1);
}else{
return sqrt(n + nestedRadical(n-1));
}
}
This code causes 1
to be the most deeply nested radical, when it should be the highest. How should should I approach this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仔细检查和分析嵌套自由基。在纸上写,即使需要。那你会更好地理解。
尝试以下操作:
Examine and analyze nested radicals carefully. Write on paper, even if needed. then you will understand better.
Try this: