我试图解决递归的练习。这次演习是在C来解决,但为了方便,我第一次试图解决它在C#中(其中,我比较习惯)。它说:
写一个程序,其中用户必须输入一个正数n是2的幂(我认为这2 ^ 0 = 1必须被排除,即使它不澄清),然后打印的特定图案与的帮助下递归函数。
例如,对于N = 8,注意中间线具有8分:
* (7 spaces)
** (6 spaces)
* (6 spaces)
**** (4 spaces)
* (5 spaces)
** (4 spaces)
* (4 spaces)
******** (0 spaces)
* (3 spaces)
** (2 spaces)
* (2 spaces)
**** (0 spaces)
* (1 space)
** (0 spaces)
* (0 spaces)
例如对于n = 4:
* (3 spaces)
** (2 spaces)
* (2 spaces)
**** (0 spaces)
* (1 space)
** (0 spaces)
* (0 spaces)
我有翻译希腊练习,所以我提前很抱歉,如果我有措辞有些不妥。我曾亲自添加所需的间距各行必须以使其更容易让你。
我做了什么:
我已经找到了递归函数,它是(我后我的计划全码)的结构:
static void Main()
{
int n;
do
{
n = int.Parse(Console.ReadLine());
}
while (!IsPowerOf2(n)) ;
PrintRecursive(n);
}
static void PrintRecursive(int stars)
{
if (stars > 2)
{
PrintRecursive(stars / 2);
Console.WriteLine(new string(' ',0) + new string('*', stars));
PrintRecursive(stars / 2);
}
else
{
Console.WriteLine(new string(' ', 0) + "*");
Console.WriteLine(new string(' ', 0) + "**");
Console.WriteLine(new string(' ', 0) + "*");
}
}
static bool IsPowerOf2(int n)
{
return (n != 0) && ((n & (n - 1)) == 0);
}
这个递归函数产生分每个可接受的N-正确序列(除了1我坚持认为它必须被排除)。
我没有做什么:
我真的找不到一个公式来计算()中的每个Console.WriteLine所需要的间距。为了获得该模式的具体格式是否正确,我一定要找到的东西来代替计数参数在String类我发起的实例。
我想,你正在寻找的是这个。有了您的两个处理功率。
static void Main(string[] args)
{
PrintStars(8, 0, 0);
}
static void PrintStars(int stars, int prefix, int suffix)
{
if(stars == 1)
{
PrintStarsToConsole(stars, prefix, suffix);
return;
}
var halfStars = stars >> 1;
PrintStars(halfStars, prefix + halfStars, suffix); // for n = 4: __**
PrintStarsToConsole(stars, prefix, suffix); // for n = 4: ****
PrintStars(halfStars, prefix, suffix + halfStars); // for n = 4: **__
}
static void PrintStarsToConsole(int stars, int prefix, int suffix)
{
Console.Write(new string(' ', prefix));
Console.Write(new string('*', stars));
Console.Write(new string(' ', suffix));
Console.WriteLine();
}