69,368
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
int fibonacci(int n)
{
if(n == 0 || n == 1)
{
return 1;
}
int result = 1;
int pre = 1;
int temp = result;
for(int i = 2; i <= n; i ++)
{
temp = result;
result += pre;
pre = temp;
}
return result;
}
int main()
{
int n;
cout << "enter: " ;
cin >> n;
cout << fibonacci(n) << endl;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 400
void my_print(int *a) //输出时把数组倒过来就是答案
{
int i;
if (a[0]<0) printf("-");
if (a[0]==0)
{
printf("0");
return;
}
for(i=abs(a[0]);i>=1;i--)
printf("%d",a[i]);
printf("\n");
}
void format(int *a) //当两个字符相加时超过10时
{
int p;
for(p=1;p<a[0]||a[p]>=10;p++)
{
if (p>=a[0]) a[p+1]=0;
a[p+1]+=a[p]/10;
a[p]=a[p]%10;
}
if (p>=a[0]) a[0]=p;
return;
}
void add(int *a,int *b,int *c) //加法的运算
{
int len,i;
if (a[0]<b[0]) len=a[0];
else len=b[0];
for(i=1;i<=len;i++)
c[i]=a[i]+b[i];
if (len<a[0])
{
for (;i<=a[0];i++)
c[i]=a[i];
c[0]=a[0];
}
else
{
for(;i<=b[0];i++)
{
c[i]=b[i];
}
c[0]=b[0];
}
format (c);
}
int main()
{
int a[MAX],b[MAX],c[MAX],i,j;
a[1]=1;a[0]=1;b[1]=1;b[0]=1;
for(i=0;i<1000;i++) //数列的1002项
{
add(a,b,c);
for(j=0; j<MAX; j++)
{
a[j] = b[j];
b[j] = c[j];
}
}
my_print(c);
getch();
return 0;
}