求c语言程序:求fibonacci数列前n个数的和?

2024-12-16 14:37:30
推荐回答(3个)
回答1:

#include
int main()
{
int f1 = 1;
int f2 = 1; //这是前两项的数值。
int sum = 0;
int n;
scanf("%d",&n); //输入N;
int i;
int temp;
if(n == 1)
{
sum = f1;
}
else if(n == 2)
{
sum = f1+f2;
}
else
{
sum = f1+f2;
for(i=2;i {
temp = f1+f2;
sum += temp;
f1 = f2;
f2 = temp;
}
}
printf("sum = %d",sum);
return 0;
}

回答2:

//fiboiacci数列:1 1 2 3 5 8 13 21...

#include

void main(void)
{
int i,n;
long a=1,b=1,c=2,d=2;//a,b为相邻两项,c为a+b,d为前面各项之和

printf("input number:");
scanf("%d",&n);
for(i=3;i<=n;i++)
{
c=a+b;
a=b;
b=c;
d=d+c;
}
printf("%ld\n",d);
}

回答3:

#include
void main()
{
int x,i;
long int f1=1,f2=1,f;
long int s=2;
printf("Enter x: ");
scanf("%d",&x);
if (x==1)
printf("s=1\n");
else if (x==2)
printf("s=2\n");
else if (x>2)
{for(i=3;i<=x;i++)
{f=f1+f2;
f1=f2;
f2=f;
s=s+f;
}
printf("s=%ld\n",s);}
}