简单的c ++嵌套for循环程序打印星形错误的正方形

时间:2017-03-04 14:47:55

标签: c++ for-loop

我尝试使用嵌套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:

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

所需的输出:

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

1 个答案:

答案 0 :(得分: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语句错了!