加减乘除科学计算
加减乘除科学计算
能东棍 发表于8个月前
加减乘除科学计算
  • 发表于 8个月前
  • 阅读 16
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

#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;
}
共有 人打赏支持
粉丝 5
博文 29
码字总数 20467
×
能东棍
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: