首页 > 解决方案 > 我的计算器代码中有一个错误,我现在不知道如何修复它

问题描述

当我们将这封信插入控制台时,它开始在第 19 行和第 42 行重复。当我通常写发票时,它对我有用。

请帮助如何解决这个问题。

图片

#include<iostream>
using namespace std;

int main()
{
    float num1, num2;
    char operator1;

    bool repeat = true;

    while (repeat)
    {

        char odgovor; //odgovor da ali ne v katerega bom spravil v bool(true / false)
        cout << "do you want to continue d(yes) or n(no) " << endl;
        cin >> odgovor;
        repeat = odgovor == 'd';

        cout << "enter the calculation" << endl;

        cin >> num1 >> operator1 >> num2; //vnos dveh števil in operatorja
        switch (operator1)
        {

        case'-':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 - num2 << endl; break;
        case'+':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 + num2 << endl; break;
        case'/':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 / num2 << endl; break;
        case'*':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 * num2 << endl; break;
        case'%':
            bool isNum1Int, isNum2Int;
            isNum1Int = ((int)num1 == num1);
            isNum2Int = ((int)num2 == num2);

            if (isNum1Int && isNum2Int)
            {
                cout << (int)num1 << " " << operator1 << " " << (int)num2 << " = " << (int)num1 %(int)num2 << endl; break;
            }
            else {
                cout << "the number must be an integer" << endl; break;
            }

        default:cout << "not valid" << endl;  break;

        }

    }
    return 0;

}

标签: c++mathcalculator

解决方案


当我们将字母插入控制台时,它开始在第 19 行和第 42 行重复。

这条线是罪魁祸首:

cin >> num1 >> operator1 >> num2;

在这里,std::cin将首先尝试从控制台读取一个整数。如果你正确输入一个整数,什么都不会发生,一切都会按预期进行。

但是,当您仅将一个字符传递给控制台时,会std::cin 失败,因为它无法在您的输入中找到一个整数。失败后std::cin,它不会尝试阻止执行以获取更多输入,此外,您的代码中没有任何内容会跳出while循环,因此它将无限期地迭代,这就是您所面临的。

要解决此问题,您可以检查是否std::cin失败并在需要时相应地中断循环:

// ...

cin >> num1 >> operator1 >> num2;
if (cin.fail())
    break; // Break out of the loop in case of failure

// ...

推荐阅读