Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 打印带嵌套循环的直角三角形_C#_For Loop - Fatal编程技术网

C# 打印带嵌套循环的直角三角形

C# 打印带嵌套循环的直角三角形,c#,for-loop,C#,For Loop,这是我的循环: int height=Convert.ToInt32(Console.ReadLine()); Console.WriteLine(“通过“+height+”直角三角形打印“+height+”); for(int i=1;iWriteLine会在字符串末尾隐式添加一个换行符。Write不会。请按照两个循环每次迭代中的每个步骤查找错误。对于第一次迭代,当i为1时,您会得到: * <-- WriteLine (i == 1), adds a newline *

这是我的循环:

int height=Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“通过“+height+”直角三角形打印“+height+”);

for(int i=1;i
WriteLine
会在字符串末尾隐式添加一个换行符。
Write
不会。请按照两个循环每次迭代中的每个步骤查找错误。对于第一次迭代,当
i
为1时,您会得到:

*       <-- WriteLine (i == 1), adds a newline
*       <-- Write (i == 1, j == 1), does not add a newline! Next character will be printed after this * on the same line!

你看到bug在哪里吗?你在当前行的中间打印新行字符;你应该在行的末尾打印它。

,这意味着对于每个迭代,它都在两条不同的行上编写

要解决此问题,您只需在循环末尾添加一个
WriteLine()
,这样您就可以
Write()
一行中的每个星,然后
WriteLine()
这样下一次迭代将从下一行开始:

// For each row
for (int row = 1; row <= height; row++)
{
    // For each column in the row
    for (int col = 1; col <= row; col++)
    {
        // Write a star
        Console.Write("*");
    }

    // End the row
    Console.WriteLine();
}

如前所述,问题在于Console.WriteLine(“”*)中。如果计算运行代码段后生成的行数,您会发现每次都有一个额外的行。 运行高度为5的代码段将实际生成6行星星:

*
**
***
****
*****
*****
这是因为在你进入内部循环之前,你正在打印一个星号,然后开始新的一行。 为了简化这个过程,最好为每个循环分配一个角色,内部循环应该是输出星号的循环,外部循环负责打印新行

下面是我的想法。我修改了for循环,使用变量row和col。我发现它更容易理解

for (int row = 1; row <= height; row++) {
   for (int col = 1; col <= row; col++){
      Console.Write("*");
   }
   Console.WriteLine();
}

for(int row=1;row如果没有至少一个
LINQ
解决方案,什么样的循环操作才能完成?好的,给你:

    private static void TestRightAngle(int height)
    {
        var l = new int[height];
        int i = 0;
        l.ToList().ForEach(f => Console.WriteLine(string.Empty.PadRight(++i, '*')));
    }

是的,它是免费的,而且效率很低,但它确实有“jene Sais qoi”…它有
LINQ
-吸引力。

这个输出是为
4
生成的。对于
5
,输出中有六行。这是因为
WriteLine
被调用了五次,总共六行。显然我们的想法是一样的。:)@RufusL是的,看起来像是hahaI看到了。我在每行打印一个额外的星星,因为每一个int我都打印一个星星。谢谢!
for (int row = 1; row <= height; row++) {
   for (int col = 1; col <= row; col++){
      Console.Write("*");
   }
   Console.WriteLine();
}
    private static void TestRightAngle(int height)
    {
        var l = new int[height];
        int i = 0;
        l.ToList().ForEach(f => Console.WriteLine(string.Empty.PadRight(++i, '*')));
    }