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

时间:2015-04-25 10:22:58

标签: c++ while-loop

我的代码有问题,但我无法弄清楚如何修复它。

我使用Dev-C ++在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 ++的新手,欢迎提出改进建议。

1 个答案:

答案 0 :(得分:2)

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

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