创建空心方块c ++

时间:2013-08-28 02:31:04

标签: c++

我编写了这段代码但不知何故,当它要求用户输入一个新数字来创建一个正方形时,它不会打印正方形。任何人都可以解释/帮助我吗?

// 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++;
        }

2 个答案:

答案 0 :(得分:2)

我看不到将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 。想想可能性:

while ( num < 1 || num > 20 )

如果您希望在范围为1..20的值 之外继续循环,则应使用:

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

然后您最终得到以下内容:

b

您的代码存在许多其他潜在问题,例如:

  • 你似乎有两次外圈。
  • 您似乎没有定义numnum
  • 您似乎没有在外部循环(检查它)之前设置while ( num > 1 || num < 20 )
  • 我怀疑您打算在cin.ignore()调用后立即关闭{{1}}循环,因为它意味着继续运行,直到您获得1到20之间的值并且然后绘制广场。就目前而言,即使您输入99,也会绘制一个正方形。

答案 1 :(得分:0)

可能不是最好的代码 - 但它可以在六行中完成。到此为止。

   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;
    }