C#用迭代求解

时间:2015-07-22 02:52:22

标签: c# loops 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();
}

2 个答案:

答案 0 :(得分:0)

您当前的代码只打印一行。您需要一个外部循环来打印多行,再加上条件检查以了解是否在行的相应列中打印行号或字符串。

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

答案 1 :(得分:0)

如果我能正确理解您的要求,您可以使用嵌套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