下面的程序将重复宽度,但我也想重复高度输入。
int main ()
{
int height;
int width;
int count;
int hcount;
string character;
cout << "input width" << endl;
cin >> width;
cout << "input height" << endl;
cin >> height;
cout << "input character" << endl;
cin >> character;
for (hcount = 0; hcount < height; hcount++);
{
for (count = 0 ; count < width; count++)
cout << character;
cout << endl;
}
我需要添加另一个 for 循环吗?我不知道如何让它重复。我尝试添加另一个 for 循环但更改了高度和宽度的顺序:
for (count = count < width; count++)
{ (count = count < height; hcount++)
cout < character;
cout << endl;
但没有运气。
最佳答案
for
循环在它后面的单个语句上运行 so
for (hcount = 0; hcount < height; hcount++);
相当于
for (hcount = 0; hcount < height; hcount++)
;
所以你的第一个循环什么都不做。如果您删除结尾的分号
for (hcount = 0; hcount < height; hcount++)
您将获得所需的嵌套循环。
还要注意
for (count = 0 ; count < width; count++)
cout << character;
cout << endl;
实际上是
for (count = 0 ; count < width; count++)
cout << character;
cout << endl;
如果您希望这两行都在内部循环中执行,您需要将它们放在大括号内 {}
for (hcount = 0; hcount < height; hcount++) {
for (count = 0 ; count < width; count++) {
cout << character;
cout << endl;
}
}
关于c++ - 如何让循环重复输入的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743042/