在C语言中,使用用户输入值计算方程式不会给出预期的结果吗?

时间:2019-02-27 07:20:32

标签: c arrays loops math

我正在为我的课做作业,但被卡住了。任务是:

编写一个递归程序以预先计算斐波纳契数并将其存储在数组中。斐波那契公式为Fib(0)= 1,Fib(1)= 1和Fib(i)= Fib(i-1)+ Fib(i-2)。将第i个斐波那契数存储在索引i中。循环读取i并打印i和ith斐波那契数。使用-1退出循环。我的输出是错误的,但我不知道如何解决。我已经尝试了一段时间,但我无法指出我的错误。

我的代码是

#include <stdio.h>  
double Fib[50]; //globally declared 
int fib(int i)
{               
    for(i=0; i<50; i++) //loop to scan 
    {   
        scanf("%lf", &Fib[i]); //scan and store numbers in an array
        if (Fib[i]==-1) //i =-1 will end loop
            break;
    }       
    Fib[i]= Fib[i-1]+Fib[i-2];//formula     
    if(Fib[i]==0||Fib[i]==1) //i=0 and i=1 will print 1
        Fib[i]=1;
    else if(i>1) //performs the operation with the formula
        printf("%d  %lf\n", i, Fib[i]);
}   
int main()
{
    int i=0;
    fib(i); 
return 0;    
}
Expected result:
user input: 4 10 20 15 5 -1
output:
4 5.000000
10 89.000000
20 10946.000000
15 987.000000
5 8.000000  

My output:
5  20.000000

1 个答案:

答案 0 :(得分:1)

几点

  • 您的程序不是递归的
  • 先使用递归函数计算所有Fib,然后再计算 循环处理用户输入

下面的代码具有处理用户输入,进行递归的结构

#include <stdio.h>

// It would make sense for this to store unsigned long long instead of double
// because Fibonacci numbers are always positive integers
unsigned long long Fib[50];

// Your assignment specifically said use a recursive program to compute Fib.
// This is not a recursive function, but it is correct, I will leave the
// recursion for you to work out
void populateFib() {
    Fib[0] = 1;
    Fib[1] = 1;
    unsigned i;
    for (i = 2; i < 50; ++i)
        Fib[i] = Fib[i - 1] + Fib[i - 2];
}

int main() {
    // First compute Fib
    populateFib();

    // Deal with user input in an infinite loop
    for (;;) {
        int input;
        scanf("%d", &input);

        // Condition for breaking the infinite loop
        if (input == -1)
            break;

        // Sanity check the user won't read out of bounds
        if (input < 0 || input >= 50) {
            printf("No!\n");
            continue;
        }

        // Display what the user wants
        printf("%d %llu\n", input, Fib[input]);
    }
    return 0;
}