C#使用递归打印星号金字塔。

问题描述 投票:-3回答:1

我有一个问题是:写一个得到n个数字(整数)的函数,程序将按n个数字的高度打印一个星号*金字塔,第一行函数将打印一个 "*",下一行将打印两个*,以此类推。

   *

  ***

 *****

*******

我必须用递归的方式写程序,不需要任何循环...所以一开始我写了这段代码,输入一个高度,然后把一个数字送入一个函数,打印出图案,我知道我需要做另一个打印空格的函数,但是我很困惑,不知道如何用递归的方式来做...。

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-studio recursion pyramid a-star
1个回答
2
投票

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

  // 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);

0
投票

下一行应该比上一行少一个空格。

如果你有4行,最后一行有0个空格,所以第一行有4个空格。

© www.soinside.com 2019 - 2024. All rights reserved.