循环麻烦

时间:2018-11-02 18:43:32

标签: c++

我有一个简单的程序来制定任何给定数字的表,但是最后我希望提示用户结束程序或制定另一张表。但是不会发生循环。(我只是一个循环新手)

int table(){
  int tablenumber;
  int tablecount;
  cout<<"which number's table would you like to print?"<<endl;
  cin>>tablenumber;
  cout<<"till which number would you like to multiply it?"<<endl;
  cin>>tablecount;
  for(int i=0; i<=tablecount; i++){
  cout<<tablenumber<<" X "<<i<<"="<<tablenumber*i<<endl;
  }
}

int main(){
  bool yes=true;
  bool no=false;
  char answer= yes;
while(answer==true){
  table();
  cout<<"would you like to formulate another table?(yes/no)"<<endl;
  cin>>answer;
  }

 return 0;
}

2 个答案:

答案 0 :(得分:1)

问题在于answerchar,而您正在尝试将其与bool进行比较。 truefalse始终为零(false)和任何非零数字(true),因此一旦您将信息读入answer,输入的char的ascii值就不会等于0(false的int值)。

因为answery,所以Y等于是(或answer / char时,读取输入并循环。或将answer设为string

string answer = "yes";
while (answer == "yes" || answer == "Yes") {
    //code
}

答案 1 :(得分:0)

作为@GBlodgett回答的后续措施,我想指出一个可能的解决方案:

do{
   table();
   cout<<"would you like to formulate another table?(yes/no)"<<endl;
   cin >> answer;
}while(answer == "yes");

如您所见,您甚至不需要这两个布尔。但是,由于您希望答案为“是”,因此需要将answer设为string。祝你好运!