在 y/n 响应后保存 while 循环信息



我的代码有问题,但我不知道如何解决它。

我在C++中使用 Dev-C++ 制作了一个计算器。我做了一个while循环,这样用户就不必重新启动程序就可以再次使用它。我正在尝试添加先前计算的答案在下一次计算中使用的功能,但代码被跳过了。

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    string username;
    float num1, num2, answer;
    string berekening;
    string again;
    float oldanswer;
    string oldanswerq;
    again = "y";
    cout << "Hello who are you?" << endl;
    cout << "" << endl;
    cin >> username;
    cout << "" << endl;
    cout << "well hello " << username << endl;
    cout << "" << endl;
    while (again == "y"){
    oldanswer = answer;
        if (oldanswer == 0)    {
            cout << "what is the first number you wanna put in " << username << endl;
            cout << "" << endl;
            cin >> num1;
        }
        else {
            cout << "do you wanna use your old answer? y/n" << endl;
            cout << "" << endl;
            cin >> oldanswerq;
        }
        cout << "" << endl;
        cout << "+, -, x or ÷(u can use / instead of ÷" << endl;
        cout << "" << endl;
        cin >> berekening;
        cout << "" << endl;
        cout << "and what is the second number " << username << endl;
        cout << "" << endl;
        cin >> num2;
        cout << "" << endl;
        if (berekening == "+"){
            answer = num1 + num2;
        }
        else if (berekening == "-"){
            answer = num1 - num2;
        }
        else if (berekening == "x"){
            answer = num1 * num2;
        }
        else if (berekening == "/"){
            answer = num1 / num2;
        }
        else if (berekening == "÷"){
            answer = num1 / num2;
        }
        cout << username << ", you choosed " << berekening << " what i did was: " << num1 << berekening << num2 << "=" << answer << endl;
        cout << "" << endl;
        cout << username << ", do you wanna go again? y/n" << endl;
        cout << "" << endl;
        cin >> again;
        cout << "" << endl;
    }
}

我是C++新手,欢迎提出改进建议。

您将oldanswer设置为等于循环外的newanswer。它应该在循环内完成。

在比较float时,您也不应该使用==,因为它们很少完全等于某物(小数只能精确到计算机上的一定数量)。

最新更新