【问题标题】:decision making and recursive functions决策和递归函数
【发布时间】:2018-12-28 14:53:10
【问题描述】:

我想制作一个没有 GUI 的计算器,但我遇到了这样的问题

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

当用户输入除了是或否之外的输入时,我希望程序再次询问用户是否要再次使用计算器。 但我不知道怎么做。我用了递归函数,但是用户输入错误的次数,所以程序会问“用户要不要用计算器?”

【问题讨论】:

  • 简单的while 循环应该为您完成这项工作。为什么要递归?

标签: c++


【解决方案1】:

你可以这样做 -

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

【讨论】:

  • 我在while中找到了我的问题的答案
【解决方案2】:

我猜你想要这样的东西,

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 2021-03-17
    • 2017-03-18
    • 1970-01-01
    • 2022-01-13
    • 2016-05-11
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多