我正在为我的 C++ 使用 xcode。这是一个简单的命令行计算器。 这是我目前所拥有的:
//
// main.cpp
// test
//
// Created by Henry Bernard Margulies on 8/21/13.
// Copyright (c) 2013 Henry Bernard Margulies. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool loopy = true;
cout << "\nCalculator\n";
while (loopy == true)
{
bool gooy;
double answ; // answer
double fn; // first number
double sn; // second number
string opersym; // operation symbol
string oper; // operation
string more; // rerun the program or not
cout << endl << "Operation please (+, - , x or d): "; //Problem1
cin >> oper;
if (oper == "+") //makes sure operation is viable
{
gooy = true;
}
if (oper == "-")
{
gooy = true;
}
if (oper == "x")
{
gooy = true;
}
if (oper == "d")
{
gooy = true;
} //does the above
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
if (gooy == true)
cout << endl << "First number please: ";
if(!(cin >> fn)) //makes sure it is a number
{
cerr << endl << "Enter a number next time, please try again"; //complaint
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
cout << endl << "Next number: ";
if(!(cin >> sn))
{
cerr << endl << "Enter a number next time, please try again";
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
opersym = oper;
if (oper == "+")
answ = fn + sn;
if (oper == "-")
answ = fn - sn;
if (oper == "x")
answ = fn * sn;
if (oper == "d")
{
opersym = "÷";
answ = fn / sn;
}
cout << endl << "You entered: " << fn << " " << opersym << " " << sn << ". And it equals " << answ;
cout << endl << "Want more? y/n: ";
cin >> more;
if (more == "n")
{
cout << endl << "Okay, I'm not wanted. Shutting down. :(";
return(0);
}
if (more == "y")
{
cout << endl << "Back to work!";
}
else
{
cout << endl << "Since you can not be bothered to type it right, I'll take it as a no. :(";
return(0);
}
}
}
}
return 0;
}
我有几个要求:
- 首先,似乎只有除法才有效。检查要求操作的 main 的第一部分并确认它。它不想为 +、- 或 x 工作,而只为 d
2.查看名为problem2的两条评论。在这些部分继续;并打破;不要正确重启计算器。我想回到 while 循环的开头,据说 goto 不稳定且不好。
3.你能纠正我的代码吗?我不是专家,整件事都做得很脏。请告诉我更好的逻辑,使代码更短、更快和更稳定。
谢谢! 附言。我是一个 12 岁的 child ,正在通过互联网自学 C++,所以请不要让我松懈,像对小狗说话一样解释事情。
最佳答案
您的问题是 if (oper == "d")
之后的 else 如果操作不是 d,则 else 子句将激活,即使之前选择了一个操作。试试这个。
if (oper == "+")
{
gooy = true;
}
else if (oper == "-")
{
gooy = true;
}
else if (oper == "x")
{
gooy = true;
}
else if (oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
现在最后的 else 只有在所有之前的 else 子句都被激活时才会被激活。
或者
if (oper == "+" || oper == "-" || oper == "x" || oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
break
退出它所在的循环。改为尝试 continue
。它回到循环的顶部,如果条件为真,则重新开始。
尝试在靠近使用它们的地方声明变量。例如 answ 和 opersym 直到循环后期才使用。您可以将它们声明为 if (gooy == true)
关于C++ 对我的命令行计算器进行故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371251/