请解释一下这个c++ for循环,而不是for循环.更新2
Please explain this c++ for loop, iside a for loop. Update 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
我想这个谜已经解开了!谢谢每个人回答我的问题:)我感谢你的帮助!
它实际上没有构造任何东西,因为它没有编译。:/
将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 << "*"
放入内循环来实现这一点。外循环在长度写入后放置一个换行符。输出如下所示:
****************
****************
****************
****************
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- C++ Python 循环"for i, num in enumerate(list):"版本
- C 多循环 for () 基础知识
- 没有条件值的 FOR 循环"for (int i = 1; ; i++)"无法正常工作
- 为用户提供循环for循环的选项
- 打破循环for循环