加減乘除科學計算

#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;
}
相關文章
相關標籤/搜索