返回给定索引的值作为Fibonacci序列的输入

问题描述 投票:0回答:2

所以这个。

//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。

java fibonacci
2个回答
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;
}

如果它不必是递归的,那么我认为这可能有效。没有测试过,但试图回答你的问题


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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.