创建空心正方形c++

creating hollow square c++

本文关键字:c++ 正方形 空心 创建      更新时间:2023-10-16

我已经写了这段代码,但不知怎么的,当它要求用户输入一个新数字来创建一个正方形时,它不会打印正方形。有人能给我解释一下吗?

// ask user to repeat the process again at end of the first promt
while ( num > 1 || num < 20 )
    {
  ask user to repeat the process again at end of the first promt
    while ( num > 1 || num < 20 )
    {
        // ask user t enter a square
        cout << "Please enter size of square between #1-20: n";
        cin >> buf; num = atoi (buf.c_str());
        cin.ignore(1000, 10);

        // process of printing square
        while ( num >= a)
        {
            b = 1;
            while ( num >= b )
            {
                if ( a == 1 || a == num || b == 1 || b == num )
                    cout << "*";
                else
                    cout << " ";
                b++;
            }
            cout << endl;
            a++;
        }

我没有看到将a初始化为1的代码,所以它可能有一些任意值。如果该任意值大于num,则外部循环将永远不会启动。

值得一提的是,在这种情况下,我将使用for循环,因为您事先知道限制是什么,类似于以下伪代码:

# Top line
for i = 1 to num (inclusive):
    output "*"
output newline
# Middle lines
for i = 2 to num-1:
    output "*"               # Left char
    for j = 2 to num-1:      # Middle chars
        output " "
    output "*" and newline   # Right char
# Bottom line
for i = 1 to num (inclusive):
    output "*"
output newline

这样就不必担心循环体中的条件检查了。

一个很好的经验法则是,对于已知的迭代开始前计数使用for,对于预先不知道迭代频率的循环使用while

另一个可能的问题是你的状况:

while ( num > 1 || num < 20 )

不管num的值是多少,这总是正确的,因为您使用的是逻辑或||。思考各种可能性:

num <= 1     : false or true  -> true
num == 2..19 : true  or true  -> true
num >= 20    : true  or false -> true

如果你想在值在1..20范围之外的情况下继续循环,你应该使用:

while ( num < 1 || num > 20 )

然后你会得到以下结果:

num <  1     : true  or false -> true
num == 1..20 : false or false -> false
num >  20    : false or true  -> true

你的代码还有很多其他潜在的问题,也就是说:

  • 你似乎有两次外环在里面
  • 您似乎没有定义bnum
  • 您似乎没有在外循环(检查它)之前设置num
  • 我怀疑您的意思是在cin.ignore()调用后立即关闭while ( num > 1 || num < 20 )循环,因为它意味着继续进行,直到您得到一个从1到20的值,然后绘制正方形。目前,即使您输入99,也将绘制一个正方形

可能不是最好的代码,但它可以在六行中完成。给。

   for (int y = o; y < height; ++ y) {
       for (int x = 0; x < width; ++x) {
          cout << (y == 0 || y == (height - 1) || x == 0 || x == (width - 1) ? '*' : ' ' );
       }
       cout << endl;
    }