通过循环(n-2)+(n-1)=(n)(n>2)这个表达式计算第n项数值,每循环一次赋值一次如(n-2)->(n-1),(n-1)->(n)然后在计算下一项。下面展示代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int Fib(int n)
{
int a = 1;
int b = 1;
int sum = 0;
if (n <= 2)
return 1;
else
{
while (n > 2)
{
sum = a + b;
a = b;
b = sum;
n--;
}
return sum;
}
}
int main()
{
int count = 0;
int n = 0;
scanf("%d", &n);
int ret = Fib(n); //创建Fib()函数并用变量ret接收返回值
printf("%d", ret);
return 0;
}