2017-03-04 38 views
-4

我试图用嵌套for循环打印一个正方形,但它总是像下面的形状,而且我不知道错误在我的代码中的位置简单的C++嵌套for循环程序来打印带有星号的方块错误

#include<iostream> 
using namespace std; 

int main() 
{ 
    int size=0; 
    cout << " enter hte size of the square :: " << endl; 
    cin >> size; 

    for(int i = 0 ; i != size; i++) 
    { 



     for(int j=0; j != size; j++) 
     { 
      if (i == 0 || i == size-1 || j == 0 || i == size-1) cout << "* "; 
      else cout << " "; 
     } 

     cout << endl; 

} 
    return 0; 
} 

the output: 

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

所需的输出中:

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

+0

你期望输出什么? –

+0

我编辑的帖子更清晰 – Nashat12

+0

用铅笔和纸张运行算法的时间。要特别注意你写'i'的地方和你写'j'的地方。总之,仔细阅读。 –

回答

1
#include<iostream> 
using namespace std; 

int main() 
{ 
    int size=0; 
    cout << " enter hte size of the square :: " << endl; 
    cin >> size; 

    for(int i = 0 ; i != size; i++) 
    { 



     for(int j=0; j != size; j++) 
     { 
      if (i == 0 || i == size-1 || j == 0 || j == size-1) cout << "* "; 
      else cout << " "; 
     } 

     cout << endl; 

} 
    return 0; 
} 

你的if语句错了!

+0

@Smit下次打入MC25并发表评论。 – LogicStuff

+0

什么是MC25? ... – Smit