(0): 0
(1): 1
(2): 1
(3): 2
(4): 3
(5): 5
(6): 8
(7): 13
(8): 21
(9): 34
(10): 55
…
(99): 218922995834555169026
(100): 354224848179261915075
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
int fib(int n){
int a=0,b=1;
if(n<0){
cout<<"ERROR"<<endl;
return -1;
}
else if(n<2){
cout<<n<<endl;
return n;
}
// times记录迭代次数,每次做a=a+b 和b=a+b操作,一次计算出两个值,所以times折半了
// n从2开始 2,3 4,5
int times = n/2;
while(times--){
a=a+b;
b=a+b;
}
// 判断输出a还是b
if(n%2==0){
cout<<a<<endl;
return a;
}else{
cout<<b<<endl;
return b;
}
}
int main()
{
int n;
cout<<"请输入斐波那契第几项:(数字不能太大哦)";
cin>>n;
fib(n);
return 0;
}
上面的int类型只能处理小数字,
int改为long long处理的数字稍微多点,但是不可以处理第99项
int改为double可以处理第99项,有个ACM的在线测试题目就是用double写
下面改用char数组来处理,可以处理很大的数字
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
// 数组最大的位数
#define N 100
void show(char *s){
int i;
// 跳过前面的0不输出
for(i=N-1;i>=0;i--){
if(s[i]!='0')
break;
}
if(i<0){
cout<<'0'<<endl;
return;
}
// 输出数字
for(;i>=0;i--){
cout<<s[i];
}
cout<<endl;
}
// c数组加d数组,结果给c
void add(char *c,char *d){
int i=0;
for(i=0;i<N;i++){
int t1=c[i]-'0';
int t2=d[i]-'0';
int r = t1+t2;
// 区分要不要进位两种情况
if(r<9){
c[i]=r+'0';
}
else{
// t1记录当前位
t1=r%10;
c[i]=t1+'0';
// t2记录进位的数字
if(i+1>N){
cout<<"存储位数不够了"<<endl;
return;
}
t2=r/10 +(c[i+1]-'0');
c[i+1] = t2+'0';
}
}
}
char a[N],b[N];
void fib(int n){
if(n<0){
cout<<"ERROR"<<endl;
return;
}
else if(n<2){
cout<<n<<endl;
return;
}
// times记录迭代次数,每次做a=a+b 和b=a+b操作,一次计算出两个值,所以times折半了
int times = n/2;
while(times--){
add(a,b); //a数组加b数组,结果给a数组
add(b,a); //a数组加b数组,结果给b数组
}
// 判断输出a数组还是b数组
if(n%2==0){
show(a);
}else{
show(b);
}
}
int main()
{
// 初始化为0和1
a[0]='0';
b[0]='1';
int i;
for(i=1;i<N;i++){
a[i]='0';
b[i]='0';
}
int n;
cout<<"请输入斐波那契数列第几项:(数字可以输入很大哦)";
cin>>n;
fib(n);
getchar();
return 0;
}