有五个人坐在一起,问第五个人多少岁?他说比第四个人大2岁, 问第四个人, 他说比第三个人大2岁, 问第三个人, 他说比第二个人大2岁, 问第二个人 他说比第一个人大2岁, 问第一个人, 第一个人说他10岁,请问第五个人多少岁?
使用递归
1 : 10
2 : 12
3: 14
4 : 16
5 : 18
方法一
#include <stdio.h>
int getAge(int n)
{
if (n == 1)
{
return 10;
}
else
{
return getAge(n - 1) + 2;
}
};
int main()
{
int n = 5;
int age = getAge(n);
printf("The age of the person after %d years is %d", n, age);
return 0;
}
方法二
#include <stdio.h>
int i = 1;
int factorial(int num)
{
// printf("%d\n", i);
if (i == 5)
{
return num;
};
i++;
return num + factorial(2);
};
int main()
{
int num = 10;
int result = factorial(num);
printf("第%d个人是: %d岁\n", i, result);
return 0;
};