加减乘除科学计算

原创
2017/05/17 17:22
阅读数 43
#include<iostream>
#include<stack>
#include <string>
#include <vector>


//判断 new_op > old_op
bool CompareOp(const std::string& new_op, const std::string& old_op)
{
	if (new_op == "+" || new_op == "-")
	{
		if (old_op == "+" || old_op == "-" || old_op == "/" || old_op == "*")
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	else
	{
		if (old_op == "/" || old_op == "*")
		{
			return false;
		}
		else
		{
			return true;
		}
	}


}

//中缀转后缀
std::vector<std::string> InfixToPostfix(const std::vector<std::string>& infix_list)
{
	std::vector<std::string> result;
	std::stack<std::string> operator_stack;

	for (const auto& input : infix_list)
	{	
		if (input == "+" || input == "-" || input == "*" || input == "/")
		{
			while (true)
			{
				if (operator_stack.empty())
				{
					operator_stack.push(input);
					break;
				}
				else
				{	
					//比较当前运算符和栈顶的运算符的优先级,栈顶优先级大于等于当前的运算符时,写入结果中
					const auto& top_operator = operator_stack.top();
					if (CompareOp(input, top_operator))
					{
						operator_stack.push(input);
						break;
					}
					else
					{
						result.push_back(top_operator);
						operator_stack.pop();
					}
				}
			}
		}
		else
		{
			//数字直接写入结果中
			result.push_back(input);
		}
	}

	while (!operator_stack.empty())
	{
		result.push_back(operator_stack.top());
		operator_stack.pop();
	}
	
	return std::move(result);
}


//计算后缀表达式的结果
float CalcPostFix(std::vector<std::string> infix_list)
{
	std::stack<float> number_stack;
	for (auto input : infix_list)
	{
		if (input == "+" || input == "-" || input == "*" || input == "/")
		{	
			//遇到运算符, 弹出栈顶的两个数字进行计算,并把计算结果入栈
			//注意顺序,先弹出的应该是是右边的数字
			auto num2 = number_stack.top();
			number_stack.pop();

			auto num1 = number_stack.top();
			number_stack.pop();

			if (input == "+")
			{
				number_stack.push(num1+num2);
			}
			else if (input == "-")
			{
				number_stack.push(num1 - num2);
			}
			else if (input == "*")
			{
				number_stack.push(num1 * num2);
			}
			else if (input == "/")
			{
				number_stack.push(num1/num2);
			}
		}
		else
		{
			//数字直接入栈
			char* end;
			number_stack.push(std::strtof(input.c_str(), &end));
		}
	}

	return std::move(number_stack.top());
}

int main()
{
	const std::vector<std::string>  infix_list = { "4.2", "*", "5", "-", "6", "*", "2"};
	auto result = InfixToPostfix(infix_list);
	std::cout << CalcPostFix(result) << '\n';
	return 0;
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部