[英]Use of for loops to create shapes with asterisks
我正在学习编程测试,其中一个问题将涉及查看使用星号打印形状的代码。 下面的代码与测试中的代码相似,尽管测试题将输出不同的形状。 我对这段代码的工作方式有些茫然。 我了解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;
}
输出:
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
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
}
就像大家说的那样,不需要最后一个循环来获得此特定形状,但是由于这是供您进行测试研究的,因此请确保也要理解,因为在测试中,任何类似的形状都可能会弹出,这可能需要所有循环(否则,老师为什么要把它放在那里?。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.