2013-08-28 21 views
0

有人可以帮我吗?我把这个代码编译成第一轮很好,但是当它循环的时候它并没有正确地打印出来。我无法找到这个错误。谢谢! 当我编译Xcode的第一次它给了正确的方形空心,但是当我第二次输入它没有打印出任何正方形。CPP-方形空心 - 什么是错误?

#include <iostream> 
using std::cout; 
using std::cin; 
using std::endl; 


#include <string> 
using std::string; 
#include <cstdlib> 

int main() 
{ 
    int a; 
    int b; 
    int num=0; 
    string buf; 

    //initialize a and b 
    a = 1; 
    b = 1; 

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

     if(num < 1 || num > 20) 
      break; 

     //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

可能是因为你没有复位在'while ... true'循环中''a'。尝试在'while(num> = a)'之前放置'a = 1;'' – darthbith

回答

0

你是不是重置a和b的变量,你需要把这些行

//initialize a and b 
a = 1; 
b = 1; 

在开始while(true)循环内

0
#include<iostream> 
#include<conio> 
main() 
{ 
    int squareHeight, squareWidth; 
    cout<< "Enter Height: "; 
    cin>> squareHeight; 
    cout<< "Enter Widht: "; 
    cin>> squareWidth; 
    for(int width=1; width<=squareHeight; width++) 
    { 
    if(width <= 1) 
    for(int width=1; width<=squareWidth; width++) 
      { 
       cout<< "*"; 
      } 
     else if(width<squareHeight) 
     { 
      cout<< endl; 
for(int width2=1; width2<=squareWidth; width2++) 
     { 
     if(width2==1 || width2==squareWidth) 
        cout<< "*"; 
       else 
        cout<< " "; 
      } 
     } 
     else 
     { 
      cout<< endl; 
for(int width3=1; width3<=squareWidth; width3++) 
    { 
       cout<<"*"; 
      } 
     } 
    } 
    getch(); 
}