C ++提示用户继续或离开

时间:2015-05-30 14:43:58

标签: c++ class user-controls prompt

实际上我只是试着用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'));
}

1 个答案:

答案 0 :(得分:1)

Value: 3, Count: 2 Value: 2, Count: 1 循环不包含要重复的主体,即计算器部分。

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

我会尝试这个。

do while