ylbtech-Arithmetic:Console-算法[for,if]-有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數 |
【程序28】
題目:有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數,他說比第
3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最后
問第一個人,他說是10歲。請問第五個人多大?
1.程序分析:利用遞歸的方法,遞歸分為回推和遞推兩個階段。要想知道第五個人歲數,需知道
第四人的歲數,依次類推,推到第一人(10歲),再往回推。
using System;
namespace ConsoleApplication1
{
class Program
{
static int age(int n)
{
int c;
if (n == 1)
{
c = 10;
}
else
{
c = age(n - 1) + 2;
}
return c;
}
static void Main(string[] args)
{
Console.WriteLine("The age is {0}",age(5));
}
}
}
1.C,Execution Result(運行結果) |
The age is 18
請按任意鍵繼續. . .