首页 > 解决方案 > c# 使用递归打印星号金字塔

问题描述

我被问了一个问题:写一个函数,得到 n 个数字(整数),程序将打印一个星号 * 金字塔 n 数字的高度。在第一行,函数将打印一个“*”,然后下一行它将再打印 2 个 * 等等。这意味着如果我输入 4,结果需要看起来像这样,但是金字塔方式:

   *

  ***

 *****

*******

我必须以递归方式编写程序,没有任何循环..所以起初我写了这段代码,输入一个高度并将一个数字发送到一个打印模式的函数中,我知道我需要做另一个打印空格的函数但我对如何以递归方式进行理解感到困惑..

static void trianglePattern(int hight, int n)
    {
        if(n == 0)
        {
            return;
        }
        Console.WriteLine();
        trianglePattern(hight - 1, n + 1 * 2); 
    }
    static void Main(string[] args)
    {
        int hight;
        Console.WriteLine("enter hight:");
        hight = int.Parse(Console.ReadLine());
        trianglePattern(hight, 1);
    }

谢谢您的帮助

标签: c#visual-studiorecursiona-star

解决方案


你可以使用下面的代码它应该做你想做的事,

  // function to print a row 
                public static void printn(int num) 
                { 
                // base case 
                if (num == 0) 
                return; 
                Console.Write("*"); 

                // recursively calling printn() 
                printn(num - 1); 
                } 

// function to print the pattern 
                public static void pattern(int n, int i) 
                { 
                // base case 
                if (n == 0) 
                    return; 
                printn(i); 
                Console.WriteLine(); 

                // recursively calling pattern() 
                pattern(n - 1, i + 1); 
                }

你的主要应该是这样的:

int n = 5; // and the could be a user input using console.readLine() 
pattern(n, 1);

推荐阅读