这篇试卷C#代码做了什么?

时间:2017-03-01 06:44:38

标签: c#

我设法找出问题4的代码,但看起来不对:

    private void button1_Click(object sender, EventArgs e)
    {
        string msg = "";
        int i = 1;

        while (i < 6)
        {
            int col = 0;
            while (col < i)
            {
                msg += i;
                col++;
            }
            msg += "\n";
            i++;
        }

        MessageBox.Show(msg);
    }

使用for和if语句有更简单的方法吗?

Home Picture

同样对于问题5,我完全迷失了。

4 个答案:

答案 0 :(得分:0)

要解决问题四,您可以使用Enigmativity的解决方案。对于问题五,我会建议你这样的事情:

string output = string.Empty;
const string symbol = "*";

//Loop up to the half to print the upcomming way
for (int i = 1; i <= 5; i++)
{ 
    //Based on index i we need to print asterix
    for (int up = 0; up < i; up++)
    {
      output += symbol;
    }

    //After all asterix are written to string we need a NewLine.
    output += Environment.NewLine;
 }

 //Here we start the same part as above but reverse it
 //So counting from upper end down
 for (int i = 5; i >= 1; i--)
 {
    for (int down = 0; down < i; down++)
    {
      output += symbol;
    }

    output += Environment.NewLine;
  }

  //The Trim(); will cut any free spaces before and after the string
  //So we can easily cut the last NewLine which is inserted but not needed
  MessageBox.Show(output.Trim());

我希望代码注释能够解释我们在这里做了什么。我认为这是理解可懂度的最简单方法。两个外部for循环只是做同样的事情。首先计算一半,第二次从一半到最后计数。

答案 1 :(得分:0)

问题没有。五 如果你已经理解了上述答案,我相信你也会明白这一点。我正在做的只是打印*而不是数字,即,然后是反向循环。

private void button1_Click(object sender, EventArgs e)
{
 string msg = "";
   for (var i = 1; i < 6; i++)
   {
     for (var col = 0; col < i; col++)
     {
       msg += "*";
     }
     msg += "\n";
   }
   for (var i = 5; i >= 1; i--)
     {
        for (var col = 0; col< i; col++)
        {
          msg += "*";
        }
        msg += "\n";
     }
   MessageBox.Show(msg.Trim());
}

答案 2 :(得分:0)

问题4的

你可以尝试这个简单的代码

                for (int i = 1; i <= 5; i++)
                {
                    for(int j=0;j<i;j++)
                    {
                        Console.Write(i);
                    }
                    Console.WriteLine();
                }  
问题5的

您可以使用以下代码这绝对有效

            for (int i = 1; i <= 10; i++)
            {       
                for (int j = 1; j <= 5; j++)
                {
                    if (i >= j && i <= 5)
                    {
                        Console.Write("*");
                    }
                    else if (i > 5 && (i+j) <= 11)
                    {
                        Console.Write("*");
                    }

                }
                   Console.WriteLine();
            }

答案 3 :(得分:-2)

试试这个:

private void button1_Click(object sender, EventArgs e)
{
    string msg = "";
    for (var i = 1; i < 6; i++)
    {
        for (var col = 0; col < i; col++)
        {
            msg += i;
        }
        msg += "\n";
    }
    MessageBox.Show(msg);
}