求Fibonacci数列前40个数。这个数列有如下特点:第1、2个数为1、1。从第3个数开始,每个数是其前面两个数之和。即
F1=1 (n=1)
F2=1 (n=2)
Fn=Fn-1+Fn-2 (n≥3)
// ConsoleApplication4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//设置两个初始值此时a=1,b=1
int a=1,b=1;
//输出初始值
cout<<a<<ends<<b<<ends;
//循环计算输出第3-40个数
for (int i=2;i<40;i++)
{
//计算前两位之和放在b中第一轮a=1,b=2第二轮a=1,b=3
b=b+a;
//输出计算后b的数
cout<<b<<ends;
//用b-a就是计算之前b的数,放入a中,第一轮a=1,b=2 第二轮a=2,b=3 以此类推
a=b-a;
}
cin.get();
return 0;
}