0

我正在编写一个 C 程序来计算斐波那契数列中的特定数字,尽管我无法将序列作为数组返回......

我究竟做错了什么?

int 斐波那契(int 上限)
{
  整数计数器;
  int num1 = 1, num2 = 1;
  静态 int fibArray[1000];
  对于(计数器 = 1;计数器 < 上限;计数器 +=2)
    {
      fibArray[计数器] = num1;
      fibArray[计数器+1] = num2;
      数字 2 += 数字 1;
      数字 1 += 数字 2;
    }
  返回 &(fibArray);
}

我也得到错误:

fibonacci.c:28:警告:return 从指针生成整数而不进行强制转换

?

4

4 回答 4

3

由于您要返回指向数组的指针,因此返回类型应为int*. 这是示例代码:

int* fibonacci(int ceiling) //Modified return type
{
  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); //Return the address of the array's starting position
}
于 2011-02-27T06:47:25.740 回答
2

您想从 中返回一个元素fibArray,对吗?在这种情况下,使用return fibArray[...];,其中...是元素索引。

于 2011-02-27T06:41:43.413 回答
0

你不需要数组。您只需要两个整数来保存当前值和先前值。然后你做:

newValue = previousValue + newValue;
previousValue = newValue - previousValue;`

你应该被设置。当达到限制时,只需返回 newValue。

如果您确实想返回整个数组(您说的是“计算斐波那契数列中的特定数字”,这不是整个数列)。将函数的返回类型设为 int* 并使用数组。

于 2011-02-27T09:29:06.577 回答
-1
//you dont need all the "includes" I have in here. These are just a basic format I work with. This should get you going if you arent going already. cheers. :) 

#include<iostream>
#include<cstdlib>
#include<iomanip>
#include<cmath>
#include<stdio.h>
#include<cctype>
#include<list>
#include<string>

using namespace std;
int main()
//-------------------------------declaration of variables----------------------------------
{
   int num1, num2;
   int initial_value, final_value;
//-----------------------------------------inputs------------------------------------------
   cout << "What is your first number? :";
   cin  >> num1;
   initial_value = num1;
   cout << "What is your second number? :";
   cin >> num2;
   final_value = num2;
//-----------------------------------------dasloop----------------------------------------
   do
   {
       final_value = initial_value + final_value;
       initial_value = final_value - initial_value;
       cout  <<  final_value  <<  endl;
   }
   while(final_value <= 1000);

//---------------------------exits perfectly when greater than 1000------------------------
   cout << endl << endl;
   system("pause");
   return 0;
}
//I have it exit at 1000 because its a nice round number that allows you enough room
//to see the code, and sequence are both correct. 
于 2011-10-10T09:45:36.853 回答