-1

如何使用 for 循环打印模式?

图(3) 图(4)

   ** **
    ** **
     ** **
      ** **
                           **

我试过这个:

static void PrintPattern (int column)
{
    for (int r = 0; r <= column + 1; r++)
    {
        Console.Write("**");
        for (int c = 0; c < r; c++)
        {
            Console.WriteLine(" ");
        }
        Console.WriteLine();
    }
}     
4

4 回答 4

2

为好玩,希望我不会收到太多的-1

int depth = 4;
var rows = Enumerable.Range(0, depth + 1)
                     .Select(v => new string('\t', v) + "**" );

var oneString = string.Join(Environment.NewLine, rows);

Console.WriteLine (oneString);

印刷:

**
  **
    **
      **
        **

备注:如果你使用' '作为分隔符,而不是 tab '\t',你会得到下一个结果:

**
 **
  **
   **
    **
于 2013-03-18T17:16:23.307 回答
1
    void Main()
    {
        const int rowCount = 10;
        Console.Write("**");
        for (var rowNumber = 0; rowNumber < rowCount - 1; rowNumber++)
        {
            Console.Write("\n ");
            for (var spaceCount = 0; spaceCount < rowNumber; spaceCount++)
            {
                Console.Write(" ");
            }
            Console.Write("**");
        }
    }
于 2013-03-18T17:44:23.847 回答
0

工作得很好。. .

对于图 3:行 = 4,
对于图 4:行 = 5

    static void Main(string[] args)
    {
        int lines = 5;
        for (int i = 0; i < lines; i++)
        {
            bool flag = false;
            for (int j = 0; j < lines; j++)
            {
                if (j == i)
                {
                    Console.WriteLine("**");
                    flag = true;
                }
                else
                {
                    if (!flag)
                        Console.Write(" ");
                }
            }
        }

    }
于 2013-03-18T17:17:09.887 回答
0

我不懂 C#,但我会用 Java 帮助你。您应该根据需要更改语法(Console.Write== System.out.print&& Console.Writeline== System.out.println)。所以这里是代码:

 static void printPattern(int column){
   int spaceCount = 2;//number of spaces before **, change as needed
   int k;//number of times ** is printed each row, must remain always 1
   for(int i = 0; i < column; i++){
       System.out.println();//starts each row with a new line
       for(int j = 1; j < spaceCount; j++){
           System.out.print(" ");//prints j spaces in each row
        }
        spaceCount++;//increment spacecount each row, so j can also go + 1 
        for(k = 1; k <= 1; k++){
            System.out.print("**");//each row prints ** k times
        }
        k--;//k must remain 1
    }
}

对于图(3)调用printPattern(4);图(4)printPattern(5);

于 2016-03-08T22:35:55.727 回答