有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他 说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第1个人大两岁。最 后问第1个人,他说是10岁。编写程序当输入第几个人时求出其对应年龄。 编写函数age,形式参数为数字。每一个数字对应的年龄应由上一个数字的年龄决定,考虑采用递归函数解决。
age(5)=age(4)+2; age(4)=age(3)+2; age(3)=age(2)+2; age(2)=age(2)+2; age(1)=10
#include<stdio.h>
int Age(int i);
int main(void)
{
int i;
printf("Please enter the person whose age you want to know: ");
scanf_s("%d", &i);
printf("The person age is:%d\n", Age(i));
return 0;
}
int Age(int i)
{
int age=0;
if (i == 1)
age = 10;
else if (i > 5)
{
printf("Please enter the value in the vange of 1-5: ");
scanf_s("%d", &i);
age = Age(i);
}
else
age = Age(i - 1)+2;
return age;
}
//初学者分享,如有问题请多多指出,可以进行交流,谢谢。