我有一个简单的程序来制定任何给定数字的表,但是最后我希望提示用户结束程序或制定另一张表。但是不会发生循环。(我只是一个循环新手)
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;
}
答案 0 :(得分:1)
问题在于answer
是char
,而您正在尝试将其与bool
进行比较。 true
和false
始终为零(false)和任何非零数字(true),因此一旦您将信息读入answer
,输入的char
的ascii值就不会等于0(false的int值)。
因为answer
是y
,所以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
。祝你好运!