我正在学习编程测试,其中一个问题将涉及查看使用星号打印形状的代码。下面的代码类似于测试中的代码,但测试问题将输出不同的形状。关于这段代码是如何运作的,我有些不知所措。我理解for循环的概念,但不理解这些for循环中每个循环在程序中扮演的角色。下面是代码及其输出。
#include <iostream>
using namespace std;
int main()
{
int m, n;
for (m = 0; m<10; m++)
{
for (n = 0; n<m; n++) cout << " ";
for (n = 0; n<(19-2*m); n++) cout << "*";
for (n = 0; n<m; n++) cout << " ";
cout << endl;
}
return 0;
}
输出:
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
答案 0 :(得分:3)
for (m = 0; m<10; m++) // this one loops over the rows of the shape
{
for (n = 0; n<m; n++) cout << " "; // to leave spaces before the shape
for (n = 0; n<(19-2*m); n++) cout << "*"; // to fill the shape with *
for (n = 0; n<m; n++) cout << " "; // to leave spaces after the shape
cout << endl; // change line
}
正如这些家伙所说的那样,最后一个循环不需要得到这个特定的形状,但由于这是为了你的测试研究,所以也要确保理解,因为在测试中,任何类似的形状都可能弹出,可能需要所有循环(否则,老师为什么要把它放在那里?。
答案 1 :(得分:1)
for (m = 0; m<10; m++) //This is the main loop to print the 10 rows
{
for (n = 0; n<m; n++) cout << " "; //This loops provide all the spaces before the first element of each row
for (n = 0; n<(19-2*m); n++) cout << "*"; //prints the *s
for (n = 0; n<m; n++) cout << " "; //Not required here....you can get the same output without this.
cout << endl;
}