【问题标题】:I have a bug in my calculator code and I don't now how to fix it [closed]我的计算器代码中有一个错误,我现在不知道如何修复它[关闭]
【发布时间】:2023-03-20 08:39:02
【问题描述】:

当我们将这封信插入控制台时,它开始在第 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++ math calculator


【解决方案1】:

当我们将字母插入控制台时,它开始在第 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

// ...

【讨论】:

  • 或者:if (!(cin &gt;&gt; num1 &gt;&gt; operator1 &gt;&gt; num2)) break;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多