从C中的斐波那契序列中返回一个特定的数字

时间:2011-02-27 06:35:31

标签: c arrays arraylist fibonacci

我正在编写一个计算斐波纳契序列中特定数字的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

4 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:2)

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

答案 2 :(得分:0)

您不需要数组。您只需要两个整数,其中包含当前值和之前的值。然后你做:

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

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

如果你想要返回整个数组(你说的是“计算斐波纳契序列中的特定数字”,这不是整个序列)。使函数的返回类型为int *并使用数组。

答案 3 :(得分:-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.