具有终止字符的C ++开关案例计算器

时间:2017-09-17 20:22:24

标签: c++ while-loop switch-statement calculator do-while

我试图制作一个开关案例计算器,它会要求表达式(例如2 + 2)并打印答案,重复该过程,直到用户输入“q'。

当用户输入“q”时,我无法弄清楚如何让程序结束。下面的程序成功地要求表达,给出答案,并要求另一个。但是,当您输入错误的表达式时,它会永远重复默认情况,包括输入' q'。

我知道问题与我如何cin变量有关,考虑到操作数是double类型,而while循环也有问题,但是我不能想到任何替代方案,并且似乎不能在其他地方找到解决方案。

int main() {

double operand1;
double operand2;
char operation;
double answer;

while (operation != 'q'){

cout << "Enter an expression:""\n";
cin >> operand1 >> operation >> operand2;


     switch(operation)
{
    case '+':
        answer = (operand1 + operand2);
        break;

    case '-':
        answer = (operand1 - operand2);
        break;

    case '*':
        answer = (operand1 * operand2);
        break;

    case '/':
        answer = (operand1 / operand2);
        break;


    default:
            cout << "Not an operation :/";
            return 0;

}

    cout <<operand1<<operation<<operand2<< "=" << answer<< endl;

}
 return 0;
}

2 个答案:

答案 0 :(得分:1)

由于您一次读取3个变量,因此在控制台中键入q时,会将其分配给operand1,而不是operation,它是{{1}的终结符循环 - 因此,无限循环开始。

基本问题在于应用程序的逻辑。该代码的最快解决方案如下:

while

答案 1 :(得分:0)

一个简单的改变将解决问题:

int main()
{

    double operand1;
    double operand2;
    char operation = '8';
    double answer;


    while (operation != 'q'){

        cout << "Enter an expression:""\n";
        cin >> operand1 >> operation >> operand2;    
        switch(operation)
        {
            case '+':
                answer = (operand1 + operand2);
                break;

            case '-':
                answer = (operand1 - operand2);
                break;

            case '*':
                answer = (operand1 * operand2);
                break;

            case '/':
                answer = (operand1 / operand2);
                break;


            default:
                    cout << "Not an operation :/";
                    return 0;

        }

        cout <<operand1<<operation<<operand2<< "=" << answer<< endl;

        cout << "Wants to quit? Enter (q)"\n";
        cin >> operation;

    }
 return 0;
}