求費氏數列的第n項,遞迴函數的呼叫
(高顯忠, sjgau4311@gmail.com, 2011-01-22 05:41)
1樓
#include <cstdlib>
#include <iostream>
using namespace std;
// ----------------------------------------------
// n1= f(n);
int f(int n)// 求費氏數列的 第 n 項
{
// 0, 1, 2, 3, 4, 5, 6, . . .
// 1, 1, 2, 3, 5, 8, 13, . . .
if ((n == 0) || (n == 1)) {
return 1;
}
else {
return(f(n-2) + f(n-1));
}
}// end of f()
// ----------------------------------------------
int main(int argc, char *argv[])
{
// = 1.618= (1.0 + sqrt(5))/2.0
int n, n1, n2;
double r1;
for (n=1;n<=39;n++) {
n1= f(n);
n2= f(n-1);
r1= ((double) n1)/((double) n2);
printf("r1= %.18lf \n", r1);
}
system("pause");
return EXIT_SUCCESS;
}// end of main()