请解释一下这个c++ for循环,而不是for循环.更新2

Please explain this c++ for loop, iside a for loop. Update 2

本文关键字:循环 for 更新 c++ 解释 一下      更新时间:2023-10-16

可能是睡眠不足,

我不知道矩形是按什么顺序构造的。先长后高?

如果唯一指示的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

我想这个谜已经解开了!谢谢每个人回答我的问题:)我感谢你的帮助!

它实际上没有构造任何东西,因为它没有编译。:/

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次。

得到:

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

{语法在循环中有点错误。

为了回答你的问题,矩形从第1列开始画一个数字*,像这样画整行:

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

这是一个长= 3,高= 5的矩形

你的代码真乱。

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

由于控制台输出从左到右,因此必须先输出长度。您可以通过将cout << "*"放入内循环来实现这一点。外循环在长度写入后放置一个换行符。输出如下所示:

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