我正在做一个简单的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();
}
但它不起作用。任何人都可以帮助我。谢谢..
答案 0 :(得分:7)
int n = 5;
for (int row = 1; row <= n; row++) {
for (int col = 1;col <= n; col++) {
Console.Write("# ");
}
Console.WriteLine();
}
那样的东西?
答案 1 :(得分:4)
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
Console.Write("# ");
}
Console.WriteLine();
}
答案 2 :(得分:2)
此代码:
col <row
导致你出现问题。
将其更改为:
col <=5
它应该有效
答案 3 :(得分:2)
我认为这应该有效:
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
。
答案 4 :(得分:1)
在第一次迭代中,您将col
与row
进行比较,它们都是1.您检查一个是否高于另一个,第二个循环永远不会运行。像这样改写:
for (int row = 1; row <=5; row++) {
for (int col = 1;col <= 5 ; col++)
{
Console.Write("#");
}
Console.WriteLine();
}
第二次迭代每次需要从1运行到5次。
答案 5 :(得分:0)
这肯定有效:
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
Console.Write("# ");
}
Console.Write("\n");
}
答案 6 :(得分:-1)
for(int i=0; i<5 ; i++)
for(int j=0 ; j <5 ; j++)
Console.Write("#");
Console.WriteLine();