Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

fibonacci c-Programm with array

I'm trying to write a C program that outputs the fibonacci numbers using an iterative function. I want to use an array which containing the Fibonacci numbers The program gives me the wrong fibonacci values, I cannot see any mistake

Please help here is my programm:

    #include <stdio.h>
    
    int fibonacciL(int unsigned value){
    int i;
    const int MAX = value;
    int fibo[MAX];
    
    fibo[0]=0;
    fibo[1]=1;
    
        for(i=2;i<value+1;i++)
        {
        fibo[i]= fibo[i-1] + fibo[i-2];
        return fibo[value];
        }
    }
    
    int main(){
    int value;
    printf("Iterativ Fibonacci
");
    printf("Enter a Number:");
    scanf("%d", &value);
    printf("For the number %d the value is: %d
",value,fibonacciL(value));
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • You allocated the array fibo one element less than required.
  • You returned fibo[value] before calculating that.
int fibonacciL(int unsigned value){
    int i;
    const int MAX = value;
    int fibo[MAX+1]; /* allocate one more element so that fibo[value] become available */
    
    fibo[0]=0;
    fibo[1]=1;
    
    for(i=2;i<value+1;i++)
    {
        fibo[i]= fibo[i-1] + fibo[i-2];
    }
    return fibo[value]; /* move this to right place */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...