[英]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.