请解释这个C++ for循环,是for循环。更新2

问题描述:

它可能是睡眠不足,请解释这个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绘制了整个行是这样的:

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

这是一个长度= 3和高度= 5矩形。

+0

谢谢,请参阅我更新的问题:) – WellWellWell 2011-12-22 03:27:44

它实际上并没有任何建设,因为它不会编译。 :/

更改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

非常杂乱代码在你那里。

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