返回 C 中斐波那契数列的特定数字
我正在编写一个 C 程序来计算斐波那契序列中的特定数字,尽管我无法将序列作为数组返回......
我做错了什么?
int fibonacci(int ceiling) { int counter; int num1 = 1, num2 = 1; static int fibArray[1000]; for (counter = 1; counter < ceiling; counter+=2) { fibArray[counter] = num1; fibArray[counter+1] = num2; num2 += num1; num1 += num2; } return &(fibArray); }
我也收到错误:
fibonacci.c:28: warning: return makes integer from pointer without a cast
?
I'm writing a C program that calculates a specific number in the fibonacci sequence, though I'm having trouble returning the sequence as an array....
What am I doing wrong?
int fibonacci(int ceiling) { int counter; int num1 = 1, num2 = 1; static int fibArray[1000]; for (counter = 1; counter < ceiling; counter+=2) { fibArray[counter] = num1; fibArray[counter+1] = num2; num2 += num1; num1 += num2; } return &(fibArray); }
I also get the error:
fibonacci.c:28: warning: return makes integer from pointer without a cast
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您要返回指向数组的指针,因此返回类型应为
int*
。这是示例代码:Since you are returning a pointer to an array, the return type should be
int*
. Here is sample code:您想从
fibArray
返回一个元素,对吗?在这种情况下,请使用return fibArray[...];
,其中...
是元素索引。You want to return one element from
fibArray
, correct? In that case, usereturn fibArray[...];
, where...
is the element index.你不需要数组。您只需要两个整数来保存当前值和先前值。然后你做:
你应该被设置。当达到限制时,只需返回 newValue 即可。
如果您确实想返回整个数组(您说的是“计算斐波那契序列中的特定数字”,这不是整个序列)。将函数的返回类型设置为 int* 并使用数组。
You don't need an array. You just need two integers in which you hold current value and previous value. You then make:
and you should be set. When the limit is being hit, just return the newValue.
If you do want to return the whole array (you are saying "calculates a specific number in the fibonacci sequence" which is not the whole sequence). Make the return type of your function int* and use the array.