返回给定索引的值作为斐波那契数列的输入

时间:2018-06-27 01:27:30

标签: java fibonacci

因此,这个。

//Fibonacci Series using Recursion
class fibonacci
{
    static int fib(int n)
    {
    if (n <= 1)
    return n;
    return fib(n-1) + fib(n-2);
    }

    public static void main (String args[])
    {
    int n = 10;
    System.out.println(fib(n));
    }
}

我该如何对其进行转换,使其将索引作为参数并在该索引处返回给定的斐波那契数?所以说我输入index = 5,它应该返回8。

2 个答案:

答案 0 :(得分:0)

static int fib(int index)
{
       int counter = 0;
       int current = 0;
       int previous = 0;
       int temp = 0;
       while(counter < index)
       {
              temp = previous;
              previous = current;
              current += temp;
              counter++;
       }
       return current;
}

如果不必递归,那么我认为这可能会起作用。还没有测试过,但试图回答您的问题

答案 1 :(得分:0)

int main(){
int index, temp1 = 0, temp2 = 1, value_at_index = 0;
    printf("Enter index: ");
    scanf("%d",&index);
    if(index==1){
       printf("Fib value at index 1 = 1");
    }
    else{
        for (int i = 2; i <= index; ++i){
              value_at_index = temp1 + temp2;
              temp1 = temp2;
              temp2 = value_at_index;
        }
       printf("Fib value at index %d = ", index);
       printf("%d\n", value_at_index);
       return 0;
    }
}