gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:28:04 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于c++ - 在 y/n 响应后保存 while 循环信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29863948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com