解决斐波那契数列在函数中递归返回void
我的教授要求我们编写一个程序,使用递归来解决斐波那契数列。这很正常,但他要求我们让函数返回 void。我已经为此工作了几天,但找不到方法来做到这一点。
我:
void fibonacci(double *n,double *x,double *y,double *result) {
if(*n == 1)
*result = 0;
else if(*n == 2)
*result = 1;
else
fibonacci(--n,n,(n-1),(n+(n-1))); }
我现在做的事对吗?我从来没有用过 以前以这种方式参数,我不确定 如果我走在正确的轨道上。由于某种原因它是 不在斐波那契递归调用时进行编译, 说明指针加法无效。谢谢!
My professor has asked us to write a program that uses recursion to solve a fibonacci sequence. This is all pretty normal, but he's asked us to make our function return void. I've been working at this for a few days now and can't find a way to do this.
I have:
void fibonacci(double *n,double *x,double *y,double *result) {
if(*n == 1)
*result = 0;
else if(*n == 2)
*result = 1;
else
fibonacci(--n,n,(n-1),(n+(n-1))); }
Is what I'm doing right? I have never had to use
parameters in such ways before and I'm not sure
if I'm on the right track. For some reason it's
not compiling at the recursive call to fibonacci,
stating invalid pointer addition. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
提示:问题就在那里:
fibonacci(--n,n,(n-1),(n+(n-1)));
甚至就在那里--n
。您正在使用指针Hint: problem is there:
fibonacci(--n,n,(n-1),(n+(n-1)));
or even just there--n
. You're working with pointers编译器是对的。如果使用指针,则需要在调用中取消引用指针。
但更简单的解决方案是使用此原型(并将所有代码与其匹配):
The compiler is right. You need to dereference the pointers in the call, if you use pointers.
But the simpler solution would be to use this prototype instead (and match all code to it) :
由于这是一项作业,我不会提供工作代码,尽管这里有几点:
Since this is a homework, I won't provide working code, although a few points here:
不,不是。
首先,您要减去指向浮点的指针(在 --n 处),这可能很容易(即使您编译并运行它)产生访问冲突。它正确地抱怨了类型。该函数接受的类型是指针,我敢打赌您正在传递浮点数。
no it is not.
1st of all you are subtracting pointers to float (at --n) which might easily (even if you compile it and run it) produce access violation. It correctly complains though about types. The types that the function accepts are pointers and I bet you are passing floats.
使用此作为开始:
通过将
result
声明为引用,您的修改将更改传递的实际参数的值。由于这是 C++ 参考,因此应该优先考虑。您仍然可以将n
声明为普通值,因为您不想修改它。递归调用现在就是你的作业了:)Use this for a start:
By declaring
result
as a reference, your modification will change the value of the actual parameter passed. Since this is C++ references should be preferred. You can still declaren
as a normal value, because you do not want to modify it. The recursive call is your homework now :)我想一定是这样的:
I think it must be like this: