逆波兰计算器 – C++实现

评价:
0
(0用户)

#include <iostream>
#include <cctype>
#include <cstdlib>
#include <string>
#include <vector>
#include <stack>

#define ADD ‘+’
#define SUB ‘-‘
#define MUL ‘*’
#define DIV ‘/’

#define to_str(c) std::string({c, ‘\0’})

int priority(char oper)
{
switch (oper)
{
case ADD: case SUB: return 1;
case MUL: case DIV: return 2;
}
return 0;
}

std::vector<std::string> toInfix(std::string& expression)
{
std::vector<std::string> infix;

char str[1024];
int index = 0;

for (int i = 0; i < expression.size(); i++)
{
char c = expression[i];

if (i == 0 && (c == ADD || c == SUB))
infix.push_back(“0”);

if (isdigit(c) || c == ‘.’)
str[index++] = c;
else
{
if (index != 0)
{
str[index] = ‘\0’;
infix.push_back(str);
index = 0;
}

infix.push_back(to_str(c));

if (c == ‘(‘ && (expression[i + 1] == ADD || expression[i + 1] == SUB))
infix.push_back(“0”);
}
}

if (index)
{
str[index] = ‘\0’;
infix.push_back(str);
}

return infix;
}

std::vector<std::string> toSuffix(std::vector<std::string>& infix)
{
std::stack<std::string> stack;
std::vector<std::string> suffix;

for (auto& str : infix)
{
if (isdigit(str[0]))
suffix.push_back(str);
else
{
char c = str[0];
switch (c)
{
case ‘(‘:
stack.push(str);
break;

case ‘)’:
while (stack.top()[0] != ‘(‘)
{
suffix.push_back(stack.top());
stack.pop();
}
stack.pop();
break;

default:
if (!stack.empty() && priority(c) <= priority(stack.top()[0]))
{
suffix.push_back(stack.top());
stack.pop();
}
stack.push(str);
break;
}
}
}

while (!stack.empty())
{
suffix.push_back(stack.top());
stack.pop();
}

return suffix;
}

double calculate(double num1, double num2, char oper)
{
switch (oper)
{
case ADD: return num2 + num1;
case SUB: return num2 – num1;
case MUL: return num2 * num1;
case DIV: return num2 / num1;
}
return 0;
}

double calculate(std::vector<std::string>& suffix)
{
std::stack<double> stack;
for (auto& item : suffix)
{
if (isdigit(item[0]))
stack.push(atof(item.c_str()));
else
{
double num1 = stack.top();
stack.pop();

double num2 = stack.top();
stack.pop();

stack.push(calculate(num1, num2, item[0]));
}
}
return stack.top();
}

double calculate(std::string& expression)
{
auto infix = toInfix(expression);
auto suffix = toSuffix(infix);
return calculate(suffix);
}

int main()
{
std::string input;
while (std::cin >> input)
printf(“%s = %.4lf\n”, input.c_str(), calculate(input));

return 0;
}
————————————————
版权声明:本文为CSDN博主「Mzying2001」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41957444/article/details/116069680

本文出自:https://blog.csdn.net/qq_41957444/article/details/116069680

注册并通过认证的用户才可以进行评价!

admin:系统自动奖励,+10,  

发表评论