我尝试了下面的程序,但没有给出预期的输出。
#include<iostream>
using namespace std;
int main()
{
// Considering each box as a separate one
for(int i = 1; i <= 2; i++)
{
cout << "+---+ " << endl;
cout << "| " << i << "| " << endl;
cout << "| | " << endl;
cout << "| | " << endl;
cout << "+---+ ";
}
return 0;
}
我得到的输出:
+---+
| 1|
| |
| |
+---+ +---+
| 2|
| |
| |
+---+
请在我错过的地方帮助我。 任何帮助或暗示都将受到高度赞赏。
答案 0 :(得分:2)
您不能将每个框视为一个单独的框,因为您将它们作为字符打印到终端中,这是逐行完成的。您必须首先打印所有框的顶部,然后打印所有框的下一行等。
如果要打印可变数量的盒子,这将是解决方案:
int main() {
using namespace std;
unsigned numberOfBoxes = 10;
for (unsigned i = 0; i < numberOfBoxes; ++i)
cout << "+---+" << (i == numberOfBoxes - 1 ? "\n" : " ");
for (unsigned i = 0; i < numberOfBoxes; ++i)
cout << "| " << i << "|" << (i == numberOfBoxes - 1 ? "\n" : " ");
for (unsigned i = 0; i < numberOfBoxes; ++i)
cout << "| |" << (i == numberOfBoxes - 1 ? "\n" : " ");
for (unsigned i = 0; i < numberOfBoxes; ++i)
cout << "| |" << (i == numberOfBoxes - 1 ? "\n" : " ");
for (unsigned i = 0; i < numberOfBoxes; ++i)
cout << "+---+ ";
}
如果循环在最后一次迭代中或者添加空格,(i == numberOfBoxes - 1 ? "\n" : " ")
就是要添加新行。
答案 1 :(得分:1)
如果您在逻辑上跟踪for循环,您将看到如何一次打印一个盒子,堆叠在另一个盒子的顶部。
您需要确保在同一行上打印所有框的顶部,然后移动到所有框的主体,依此类推,直到所有框都已打印并且#34;并行&#34 ;
为此,您可以在自己的for循环中打印每一行。例如:
#include<iostream>
using namespace std;
int main()
{
for(int i = 1; i <= 2; i++) cout << "+---+ ";
cout << endl;
for(int i = 1; i <= 2; i++) cout << "| " << i << "| ";
cout << endl;
for(int i = 1; i <= 2; i++) cout << "| | ";
cout << endl;
for(int i = 1; i <= 2; i++) cout << "| | ";
cout << endl;
for(int i = 1; i <= 2; i++) cout << "+---+ ";
return 0;
}
答案 2 :(得分:1)
Maros答案的延伸:
如果您想要以表格或矩阵的形式打印多行和多列:
int main() {
using namespace std;
unsigned numberOfColumns = 2, numberOfRows = 2;
for (unsigned int i = 1; i <= numberOfRows; ++i) {
for (unsigned j = 1; j <= numberOfColumns; ++j)
cout << "+---+" << (j == numberOfColumns ? "\n" : " ");
for (unsigned j = 1; j <= numberOfColumns; ++j)
cout << "| " << j + (numberOfColumns *(i-1)) << "|" << (j == numberOfColumns ? "\n" : " ");
for (unsigned j = 1; j <= numberOfColumns; ++j)
cout << "| |" << (j == numberOfColumns ? "\n" : " ");
for (unsigned j = 1; j <= numberOfColumns; ++j)
cout << "| |" << (j == numberOfColumns ? "\n" : " ");
for (unsigned j = 1; j <= numberOfColumns; ++j)
cout << "+---+ ";
cout << endl;
}
return 0;
}
如果此矩阵超出值9,则必须添加条件。