C语言斐波那锲数列前n项求和

#include"stdio.h"
void main()
{
	int n = 20;
	int sum = 0;
	int temp1 = 1, temp2 = 1,temp;
	printf("请输入项数:");
	scanf("%d", &n);
	if(n == 1)
	{
		sum += temp1;
	}
	else if(n == 2)
	{
		sum += temp1 + temp2;
	}
	else
	{
		sum = 2;
		temp = temp1 + temp2;
		for (int i = 3; i <= n; i++)
		{
			sum += temp;
			temp1 = temp2;
			temp2 = temp;
			temp = temp1 + temp2;
		}
	}
	printf("%d\n",sum);
}

你可能感兴趣的:(C)