1

下面的程序将重复宽度,但我也想重复输入高度。

 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;

但没有运气。

4

1 回答 1

2

循环对紧随其后的单个语句进行for操作,因此

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;
    }
}
于 2013-11-02T14:41:40.407 回答