FIbonacci系列 - 代码不打印第一个学期

时间:2014-10-12 14:14:00

标签: c++ for-loop

我正在尝试使用嵌套for循环来打印Fibonacci系列,以便外循环驱动内循环执行2 ^ i次迭代。它的工作,但无论何时我运行代码,它给我o / p 2 ^ i-1 。这意味着每次错过Fibonacci系列的第一个词是' 0'。这是我写的代码

# include <iostream>
# include <math.h>
# include <iomanip>
using namespace std;
using std::cout; // to display Output in column
using std::setw; // to display Output in column

main()
{
     int x=0, y=1, c, l, next=0, ratio, ratio_n =0 , diff =0; // Usage of double to get a better precision. 


      cout << "Enter the number of terms of Fibonacci series you want" << endl;


cout << "Number" << setw(10) << "Next" << setw(12) << "Ratio"  << setw(15) << "New ratio" << setw(20) << "Difference" << endl; // Setting the headers for the columns

for ( int i = 0 ; i < 4 ; i++ )
 {
    for(int c=0 ; c < (1<<i) ; c++)    
    {
         ratio = ratio_n; 
         next = x + y;
         x = y;
         y = next;
         ratio_n = y/x;
         diff = ratio_n - ratio;   

 cout << x << setw(13) << next << setw(13) << ratio << setw(13) << ratio_n << setw(20) << diff << endl; 
    }



}
 system("PAUSE");
}

我会很感激一些建议。 谢谢

2 个答案:

答案 0 :(得分:1)

您必须首先打印前2个Fibonacci值01,然后逐步修改它们以获得整个系列。您首先设置xy的值,但不打印它们,您打印的第一个值是next的值,它已设置为x + y

答案 1 :(得分:0)

cout移至内部for循环中的第一行,然后打印x而不是next。因此,您的内部for循环将包含:

cout << c << setw(13) << x << setw(13) <<endl; 
next = x + y;
x=y;
y=next;