2011-12-22 122 views
0

它可能是睡眠不足,請解釋這個C++ for循環,是for循環。更新2

我沒有得到什麼順序矩形的構造。長度先高後高?

如果只有cout<<指示的是"*",爲什麼cin>>的值用作*的量輸出?

我知道這是小白的東西了很多的你,所以請解釋一下,好像我是一個5喲:d

的代碼編輯的內容,同樣,在英語這個時候。感謝您指出了這錯誤,需要更多的咖啡:/

#include <iostream> 

using namespace std; 

void drawRectangle (int l, int h) 
{ 
for (int line (0); line < h; line++) 
{ 
    for (int column (0); column < l; column++) 
    { 
     cout << "*"; 
    } 

    cout<<endl; 
} 
} 
int main() 
{ 
int length, height; 
cout << "Length for rectangle : "; 
cin >> length; 

cout << "Height for rectangle : "; 
cin >> height; 

drawRectangle (length, height); 

return 0; 
} 

更新1:

謝謝所有誰回答,即使代碼被搞砸。我只是想確保我的理解:

#include <iostream> 

using namespace std; 

void drawRectangle (int l, int h) 

{ 
for (int line (0); line < h; line++) //this is the outer loop 
{ 
for (int column (0); column < l; column++) //this is the inner loop 
{ 
    cout << "*"; 
} 
cout<<endl; //the length is written then jumps here to break. 

/*So, the outer loop writes the length,from left to right, jumps to the cout<<endl; for a line break, then the inner loop writes the height under each "*" that forms the length?/* 

更新2:得到了我的答案就在這裏 http://www.java-samples.com/showtutorial.php?tutorialid=326

我猜這個謎就解決了!謝謝大家回答我的問題:)我感謝你的幫助!

+0

我不認爲這是正確的語法:'用於(INT線(0);線<小時;線路++)} '。支架處於錯誤的位置? – 2011-12-22 02:16:25

+21

*所以請解釋它,就像我是一個5歲*:當一個媽媽'for'循環和一個爸爸'for'循環非常相愛時,它們嵌套在一起併產生一個編譯錯誤:['13號線:錯誤:'}'令牌之前預期的初級表達式](http://codepad.org/AvBcGf1o)當你長大了,兒子,你將學習如何發佈編譯的代碼。 – 2011-12-22 02:16:51

+0

@ todda.speot.is:這是一個很棒的解釋。也許他把一支箭射向膝蓋。 – AusCBloke 2011-12-22 02:22:03

回答

1

{語法是在環路有點不對勁。

你問題矩形爲與多個繪製*起始於列1繪製了整個行是這樣的:

* * * 
* * * 
* => * => * 
* * * 
* * * 

這是一個長度= 3和高度= 5矩形。

+0

謝謝,請參閱我更新的問題:) – WellWellWell 2011-12-22 03:27:44

3

它實際上並沒有任何建設,因爲它不會編譯。 :/

更改drawRectangle以下(通過把括號,他們應該是)將使編譯和運行(但是你認爲什麼是長度和高度都回到前):

void drawRectangle(int l, int h) 
{ 
    for (int column (0); column < l; column++) 
    { 
     for (int line (0); line < h; line++) 
     { 
      cout << "*"; 
     } 

     cout<<endl; 
    } 
} 

假設l是5和h是4(drawRectangle(5, 4))。外部for循環將迭代5次,創建5行。現在對每個那些行中,內部for循環迭代4次的,並打印'*'在每次迭代(因此****打印每個行)。一旦內for循環終止,一個新的線被印刷,並且外部的一個繼續,直到已經重複了5次。

,你會得到:

**** 
**** 
**** 
**** 
**** 
+0

謝謝,請參閱我更新的問題:) – WellWellWell 2011-12-22 03:27:26

1

非常雜亂代碼在你那裏。

void drawRectangle(int l, int h) 
{ 
    for (int column = 0; column < l; column++) 
    { 
     for (int line = 0; line < h; line++) 
     { 
      cout << "*"; 
     } 
     cout<<endl; 
    } 
} 

由於控制檯輸出由左到右的話,你必須輸出lenth第一。您可以通過將cout << "*"放入內部循環來做到這一點。外部循環在寫入長度後放置換行符。的輸出中看起來像:

**************** 
**************** 
**************** 
**************** 

與長度= 16和高度= 4

+0

謝謝,請參閱我更新的問題:) – WellWellWell 2011-12-22 03:27:52