接受多个输入(如 +、- 和平方数字)的计算器.从文本文件中提取信息

Calculator that accepts multiple inputs like +, -, and a number squared. Pulling info from text file

本文关键字:计算器 信息 数字 文本 文件 提取 输入 方数字      更新时间:2023-10-16

我有这个任务:

编写一个更好的计算器程序calc3.cpp它可以理解平方数。我们将使用简化的符号 X^ 来表示 X2。例如,10^ + 7 - 51^ 应表示 10^2 + 7 − 51^2。

假设您有一个文件公式.txt其求和公式如下:

5^; = 25 1000 + 6^ - 5^ + 1; = 1012

起初我使用了开关/案例语句,这并不完全有效,而且对我来说太难理解了。我现在正在使用 if 语句。我不确定我的 if 语句有什么问题,我认为我需要在 + 和 - 语句中的每个 if 语句中添加更多内容,但我不知道是什么。

非常感谢!

cin >> sum;                      
sum == rightNum;
while (cin >> op) { 
if(op == '^') {
sum += rightNum * rightNum;
cin >> op;
}
if(op == '+') {
cin >> rightNum;
cin >> op;
if(op == '^') {
sum += rightNum * rightNum;
}
else {
sum += rightNum;
}
}

if(op == '-') {
cin >> rightNum;
cin >> op;
if(op == '^') {
sum -= rightNum * rightNum;
}
else {
sum -= rightNum;
}
}

if(op == ';') {
cout << sum << endl;
cin >> sum;
} 
}

由于您已将收集和执行下一个操作构建到处理上一个操作的代码中,因此您构建了一个无法有效扩展的程序。而是循环获取运算符并获取正确的操作数,然后,如果可以忽略运算符优先级,则对上一个结果和操作数执行操作。如果您必须考虑运算符优先级,请忽略此答案并开始查看优先级队列和树。

类似的东西

cin >> result; // get first operand. If there is no operator, this is the answer
while (true) // loop forever!
{
cin >> op;
if (op == ';')
{
print result and exit loop.
}
cin >> operand;
switch(op)
{
case '+':
result += operand;
break;
case '-':
result -= operand;
break;
other operations go here
}
}

现在我们有一个可以处理任意数量操作的基本框架,我们可以处理 ^。最好不要将其视为操作,因为它未用作操作。它更像是一个修饰符。

如果语法看起来像 10 ^ 2,你会有一个运算符,但 10^ 没有右操作数,这会搞砸其余代码的左操作数、运算符、右操作数结构。

那么我们如何做到这一点呢?每当您从用户那里读取数字时,请查看下一个字符。如果是 ^,则乘以自己读取的数字。

T替换为所需的任何类型。

T readnumber()
{
T val;
cin >> val;
if (cin.peek() == '^')
{ // found ^
val *= val; // square the value
cin.ignore() // remove the ^ so no one else trips over it
}
return val;
}

请注意,上述内容完全忽略了输入验证,并且会错误地处理错误的输入。用户是出了名的愚蠢和糟糕的打字员。不要相信用户会给程序良好的输入。一般来说,根本不信任用户。

readnumber替换cin >>,我们会得到类似的东西

result = readnumber(); 
while (true) 
{
cin >> op;
if (op == ';)
{
print result and exit loop.
}
operand = readnumber();
switch(op)
{
case '+':
result += operand;
break;
case '-':
result -= operand;
break;
other operations go here
}
}

旁注:请考虑将cin替换为通用std::istream,以便这些函数可以与任何类型的流一起使用。

基于评论的建议:

int calculate(istream & in)
{
result = readnumber(in); 
while (true) 
{
in >> op;
if (op == ';)
{
break;
}
operand = readnumber(in);
switch(op)
{
case '+':
result += operand;
break;
case '-':
result -= operand;
break;
other operations go here
}
}
return result;
}

然后calculate坐在循环中并反复调用,直到输入用完为止。

奖励建议:使用std::getline获取由 ';" 分隔的语句

string statement;
while (getline(in, statement, ';'))
{
calculate(stringstream(statement)); 
}

getline删除了";",因此它不能用于退出calculate中的循环,但这实际上使事情变得更容易一些:您可以在stringstream为空或处于失败状态时退出,