C# 用迭代求解

C# solving with Iteration

我需要在控制台中编写代码,使行号显示在行本身及其在行中的位置。我的程序只输出一行 *****,而且我似乎无法让它输出更多。帮助将是惊人的提前感谢堆

eg 1*****
   *2****
   **3***
   ***4**

我目前有,

static void Main(string[] args)
{
    int n = 0;
    string s = "";

    //check if 2 args
    if (args.Length == 2)
    {
        if (int.TryParse(args[0], out n))
        {
            //successful parse, so use n
            s = args[1]; //second argument is character

            //draw a line of characters
            DrawChars(n, s);
        }
        else
        {
            //unsuccessful parse, so no n value
        }
    }

    //wait for user to have read output
    Console.WriteLine();
    Console.Write("Press enter to finish:");
    Console.ReadLine();
}

/// <summary>
/// Method to draw a line of characters
/// </summary>
/// <param name="n">number of characters to draw</param>
/// <param name="s">character to draw n times</param>
static void DrawChars(int n, string s)
{
    for (int i = 1; i <= n; i++)
    {
        Console.Write(s);
    }
    Console.WriteLine();
}

您当前的代码只打印一行。你需要一个外部循环来打印多行,加上一个条件检查来知道是打印行号还是打印该行适当列中的字符串。

将您的 DrawChars(int n, string s) 更改为

/// <summary>
/// Method to draw a line of characters
/// </summary>
/// <param name="n">number of characters to draw</param>
/// <param name="s">character to draw n times</param>
static void DrawChars(int n, string s)
{
    for (int row = 1; row <= n; row++)
    {
        for (int col = 1; col <= n; col++)
        {
            Console.Write(col == row ? col.ToString() : s);
        }
        Console.WriteLine();
    }
}

用法:

DrawChars(5, "*");

结果:

1****
*2***
**3**
***4*
****5

如果我能正确理解你的需求,你可以使用嵌套for循环打印:

static void Main()
        {
            const int maxLineNumber = 5;
            for (var itr = 1; itr <= maxLineNumber; itr++)
            {
                for (var innerItr = 1; innerItr <= maxLineNumber; innerItr++)
                {
                    if (innerItr == itr)
                    {
                        Console.Write(itr);
                    }
                    else
                    {
                        Console.Write("*");
                    }
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }

它将打印:

1****
*2***
**3**
***4*
****5