【问题标题】:C# solving with IterationC# 使用迭代求解
【发布时间】:2015-10-11 17:36:18
【问题描述】:

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

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();
}

【问题讨论】:

  • s="" 不是 "D" 并且我将 n 设置为 0

标签: c# loops iteration


【解决方案1】:

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

将您的 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多