2013-08-28 62 views
-2

我写了这段代码,但不知何故,当它要求用户输入一个新的数字来创建一个正方形时,它不打印正方形。任何人都可以解释/帮助我吗?创建空心广场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++; 
     } 
+0

请正确格式化您的代码。我似乎注意到你的代码中的一些注释实际上不是'//注释' – Borgleader

+0

猜你在做作业吗?考虑左侧和右侧总是相同的,即左侧为“*”,右侧为“* \ n”。你只需要用正确的字符填充中间,然后为正确的行数做 –

+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 

如果你想继续循环,而你有超出范围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,也会绘制一个正方形。
+0

我在程序的开头定义了一个。 int a; a = 1 – Aysin

+0

@Oruz,理想情况下应该在原始问题中提及。然而,你应该看看答案中还有很多其他的东西。 – paxdiablo

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