簡體   English   中英

C#中的嵌套循環

[英]Nested Loop In C#

我正在做一個簡單的C#練習。 這是問題所在:編寫一個名為SquareBoard的程序,該程序使用兩個嵌套的for循環顯示以下n×n(n = 5)模式。 這是我的代碼:

Sample output:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #

這是我的代碼:

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

但這沒有用。任何人都可以幫我。 謝謝..

int n = 5;
for (int row = 1; row <= n; row++) {
    for (int col = 1;col <= n; col++) {
        Console.Write("# ");
    }
    Console.WriteLine();
}

這樣的事嗎?

for (int row = 0; row < 5; row++)
{

    for (int col = 0; col < 5; col++)
    {
        Console.Write("# ");
    }
    Console.WriteLine();
}

這段代碼:

col <row 

給您帶來麻煩。

更改為:

col <=5

它應該工作

我認為這應該工作:

int n = 5;
for (int row = 1; row <=n; row++) 
{
    string rowContent = String.Empty;
    for (int col = 1;col <=n; col++)
    {
        rowContent += "# ";
    }
    Console.WriteLine(rowContent);
}

當然,如果您經常做這種事情,則可能要使用StringBuilder

在第一次迭代中,將colrow進行比較,它們均為1。您檢查一個循環是否高於另一個循環,並且第二個循環永遠不會運行。 像這樣重寫:

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

每次第二次迭代需要運行1到5。

這絕對有效:

        for (int i = 1; i <= 5; i++)
        {

            for (int j = 1; j <= 5; j++)
            {
                Console.Write("# ");
            }
            Console.Write("\n");

        }
for(int i=0; i<5 ; i++)

    for(int j=0 ; j <5 ; j++)
    Console.Write("#");

Console.WriteLine();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM