在特定条件下的循环和简单计算器的结尾

Loop and end of simple calculator on a specific condition

本文关键字:简单 计算器 结尾 循环 条件下      更新时间:2023-10-16

我是C 的新手,我一直在弄清楚这一点。我完成了这个简单的计算器,但我需要在其中添加两个特定条件。

*首先,如果第一个输入为数字,我需要在完成后循环。

*第二,如果第一个输入是非数字,我需要程序才能结束。

我将如何解决这个问题?谢谢。

#include <iostream>
using namespace std;
int main()
{
float num_1,num_2;

char operator_1;
cout << "Enter a number, an operator, and another number: " << endl;
cin >> num_1;
cin >> operator_1;
cin >> num_2;

cout << num_1 << " ";
cout   << operator_1 << " ";
cout  << num_2 << " = ";

switch (operator_1) 
{
    case '+':
        cout << num_1 + num_2;
        break;
    case '-':
        cout << num_1 - num_2;
        break;
    case '*':
        cout << num_1 * num_2;
        break;
    case '/':
        cout << num_1 / num_2;
        break;
}
return 0;
}

您想要类似的东西:

int main()
{
    float num_1, num_2;
    char operator_1;
    while (true) {
        cout << "Enter a number, an operator, and another number: " << endl;
        if (!(cin >> num_1)) {
            cout << "Error" << endl;
            return 0;
        }
        cin >> operator_1;
        cin >> num_2;

        cout << num_1 << " ";
        cout << operator_1 << " ";
        cout << num_2 << " = ";

        switch (operator_1)
        {
        case '+':
            cout << num_1 + num_2 << endl;
            break;
        case '-':
            cout << num_1 - num_2 << endl;
            break;
        case '*':
            cout << num_1 * num_2 << endl;
            break;
        case '/':
            cout << num_1 / num_2 << endl;
            break;
        }
    }
    return 0;
}

请注意如何捕获num_1中的错误以及while循环中的所有内容。该程序仅在第一个输入不正确的情况下结束。