【发布时间】:2019-02-27 07:20:32
【问题描述】:
我正在为我的班级做作业,但我被卡住了。任务是:
编写一个递归程序来预先计算斐波那契数并将它们存储在一个数组中。斐波那契公式是 Fib(0) = 1,Fib(1) = 1 和 Fib(i) = Fib(i - 1) + Fib(i - 2)。将第 i 个斐波那契数存储在索引 i 处。有一个循环来读取 i 并打印 i 和第 i 个斐波那契数。使用 -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
【问题讨论】:
-
关于您的代码的几点说明:为什么将
i作为参数传递给fib函数,而不是将其定义为函数内部的局部变量?在循环之后,i的值可以等于50,这是数组的超出范围。或者i的值可能小于2,这意味着i - 1和i - 2可能超出范围。 -
关于您的问题,您可能想做一些rubber duck debugging。考虑到您只有一个 single (并且是有条件的!)
printf调用,为什么您期望代码有多个输出?你的函数真的没有多大意义,而且它肯定不会计算斐波那契数列。我的猜测是你应该做一些 recursion (因为你显示的公式中使用了它)。