菲波那切数列

描述

菲波那切数列指这样的数列,数列第一个数和第二个数为1,之后的每一个数等于前者的和。现在给出一个正整数k,要求斐波那切的第k个值是多少。

mycode

# include <iostream>
# include <cstdio>
# include <math.h>
using namespace std;
int main()
{
//	freopen("C:\\Users\\Lenovo\\Desktop\\algorithm\\test.txt","r",stdin);
	int k,i=2,result=0;
	cin>>k;
	int a=1,b=1,c;
	while(true)
	{
		c=a+b;
		i++;
		if(i==k)
		{
			result=c;
			break;
		}
		a=b+c;
		i++;
		if(i==k)
		{
			result=a;
			break;
		}
		b=a+c;
		i++;
		if(i==k)
		{
			result=b;
			break;
		}
	}
	
	cout <<result<< endl;
}

例题代码

# include <iostream>
# include <cstdio>
# include <math.h>
using namespace std;
int main()
{
//	freopen("C:\\Users\\Lenovo\\Desktop\\algorithm\\test.txt","r",stdin);
	int k,a=1,b=1,sum;
	bool first = true;
	cin >>k;
	if(k<=2)
	{
		cout << 1;
	}
	else
	{
		for(int i=2;i<k;i++)
		{
			sum=a+b;
			a=b;
			b=sum;	
		}
	} 
	cout << b;
	return main();
}