(1)递归求n的阶乘:
int factorial(int x) {
if (x == 1) {
return 1;
}
else
{
return x * factorial(x - 1);
}
}
int main() {
int n;
scanf("%d", &n);
printf("%d", factorial(n));
return 0;
}
(2)递归求第n个斐波那契数:
int Fibonacci(int x) {
if (x<=2)
{
return 1;
}
else
{
return Fibonacci(x - 2) + Fibonacci(x - 1);
}
}
int main() {
int n;
scanf("%d", &n);
printf("%d", Fibonacci(n));
return 0;
}
但是使用递归算法求斐波那契数存在大量重复计算,效率非常低,所以改用循环体解决:
int main() {
int a = 1;
int b = 1;
int c = 1;
int n;
scanf("%d", &n);
while (n>2)
{
c = a + b;
a = b;
b = c;
n--;
}
printf("%d", c);
return 0;
}