决策和递归功能

时间:2018-12-28 14:53:11

标签: c++

我想做一个没有GUI的计算器,但是我有这样的问题

cout<<"calculator : ";cin>>userAnswer;
if(userAnswer=='yes'){
      //procces
} else if(userAnswer=='no'){
      //exit
} else{
      //here is the problem
}

当用户输入除“是”或“否”之外的输入时,我希望程序再次询问用户是否要再次使用计算器。 但我不知道如何我使用了递归函数,但是用户输入错误输入的次数,因此程序将询问“用户是否要使用计算器?”

2 个答案:

答案 0 :(得分:0)

您可以这样做-

while (true) {
    cout<<"calculator : ";
    while(true) {
         cin>>userAnswer;
         if(userAnswer=='yes'){
              //procces
         } else if(userAnswer=='no'){
              //exit
         } else {
              break;
         }
    }
    cout<<"Do you want to use a calculator? ";
    string feedback;
    cin >> feedback;
    if ( feedback == "yes") {
        continue;
    } else {
       break;
    }
}

答案 1 :(得分:0)

我想你想要这样的东西

string userAnswer;
cout<<"calculator : ";
cin>>userAnswer;
while(true)
{
    while(true)
    {
        cout<<"\ndoes the user want to use the calculator : ";
        cin>>userAnswer;
        if(userAnswer=="yes" || userAnswer=="no")
                break;
        else
            cout<<"only yes or no input is valid\n";
    }
    if(choice=="no")
        {
            cout<<"\nExiting from the calculator\n";
            break;
        }

        cout<<"Enter your choice: \n";
        cout<<"1-Addition\n";
        cout<<"2-Subtraction\n";

        // your stuff below
}