【问题标题】:C++ Prompt User to continue or leaveC++ 提示用户继续或离开
【发布时间】:2015-05-30 14:43:58
【问题描述】:

实际上,我只是在尝试 C++ 并在这个特定问题上停下来,而不是程序关闭,它应该询问用户他/她是要继续还是要退出。现在,据我所知,我在结尾行中编写了 do-while 代码,但它不起作用。请给它一个解决方案。谢谢!!

#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<string>

using namespace std;

class Cal
{
    public:
    int Add(int a, int b)
    {
        int res;
        res=(a+b);
        cout << "Answer is " << a << "+" << b << "=" << res << endl;
    }
    int Sub(int a,int b)
    {
        int res;
        res=(a-b);
        cout << "Answer is " << a << "-" << b << "=" << res << endl;
    }
    int Mul(int a,int b)
    {
        int res;
        res=(a*b);
        cout << "Answer is " << a << "*" << b << "=" << res << endl;
    }
    int Div(int a,int b)
    {
        int res;
        res=(a/b);
        cout << "Answer is " << a << "/" << b << "=" << res << endl;
    }
};

int main()
{
    int first, second, res, operation;

    cout<<"**********************************"<<endl;
    cout<<"******* Simple Calculator ********"<<endl;
    cout<<"**********************************"<<endl;
    cout<<"Select the Operation: "<<endl;
    cout<<"1. Addition"<<endl;
    cout<<"2. Subtraction"<<endl;
    cout<<"3. Multiplication"<<endl;
    cout<<"4. Divison"<<endl;
    cout<<"Choosen Operation is: ";
    cin>>operation;
    cout << "Enter the 1st Number: ";
    cin>>first;
    cout << "Enter the 2nd Number: ";
    cin>>second;

    switch(operation){
    case 1:
        Cal a;
        a.Add(first,second);
        break;
    case 2:
        Cal b;
        b.Sub(first,second);
        break;
    case 3:
        Cal c;
        c.Mul(first,second);
        break;
    case 4:
        Cal d;
        d.Div(first,second);
        break;
    default:
        cout<< "Please Enter a Operation";
        break;
    }

    char ans;
    do
    {
       cout<< "Do you want to continue (Y/N)?\n";
       cout<< "You must type a 'Y' or an 'N' :";
       cin >> ans;
    }
    while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}

【问题讨论】:

  • 伙计们,我想要一个完全可操作的代码,它只是 do-while 循环的工作......请帮帮我

标签: c++ class user-controls prompt


【解决方案1】:

do while 循环不包含要重复的主体,即计算器部分。

do while 中的条件看起来不正确。

我会试试这个。

int main() {
  char ans = 'N';
  do {
    // calculator stuff, better to be in a separate function

    cout << "Do you want to continue (Y/N)?\n";
    cout << "You must type a 'Y' or an 'N' :";
    cin >> ans;
  } while ((ans == 'Y') || (ans == 'y'));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多