1. 程式人生 > >用堆疊求表示式的值

用堆疊求表示式的值

#include<cmath>
#include<iostream>
#include<stack>
#include<algorithm>
#include<stdexcept>
#include<string>
using namespace std;
double execute(stack<char>&ops, stack<double>&operands)
{
	double result{};
	double rhs{ operands.top() };
	operands.pop();
	double lhs{ operands.top() };
	operands.pop();
	switch (ops.top())
	{
	case '+':
		result = rhs + lhs;
		break;
	case '-':
		result = lhs - rhs;
		break;
	case '*':
		result = rhs * lhs;
		break;
	case '/':
		result = lhs / rhs;
		break;
	case '^':
		result = pow(lhs, rhs);
		break;
	default:
		throw runtime_error{ string{"invilid operator: "}+ops.top() };
	}
	ops.pop();
	operands.push(result);
}
size_t precedence(const char op)
{
	if (op == '+' || op == '-')
	{
		return 1;
	}
	else if (op == '*' || op == '/')
	{
		return 2;
	}
	else if (op == '^')
	{
		return 3;
	}
	else
		throw runtime_error{ string{"invalid operator: "}+op };
}
int main()
{
	stack<double> operands;
	stack<char>operators;
	string exp;
	cout << "A arithmatic expression can include the oprators + - * / "
		<< " and ^ for exponentiation. " << endl;
	try
	{
		while (true)
		{
			cout << "Enter an arithmatic expression and press Enter "
				<< " - enter an empty line to end: " << endl;
			getline(cin, exp, '\n');
			if (exp.empty())
				break;
			//remove spaces
			exp.erase(remove(begin(exp), end(exp), ' '), end(exp));
			size_t index{};
			//Every expression must start with a numerical operand
			operands.push(stod(exp, &index));
			while (true)
			{
				//push the oprator on to the stack
				operators.push(exp[index++]);
				//Get rhs operand
				size_t i{};//Index to substring
				//Push rhs operand
				operands.push(stod(exp.substr(index), &i));
				//Increment expression index
				index += i;
				//If we are at end of exp...
				if (index == exp.length())
				{
					//...execute outstanding ops
					while (!operators.empty())
						execute(operators, operands);
					break;
				}
				//If we reach here ,there's anothor op...
				//If there's a previous op of equal or higher precedence excute it
				while (!operators.empty() && precedence(exp[index]) <= precedence(operators.top()))
				{
					//excute previous op.
					execute(operators, operands);
				}
			}
			cout << "result = " << operands.top() << endl;
		}
	}
	catch (const std::exception& e)
	{
		cerr << e.what() << endl;
	}
	std::cout << "Calculator ending...." << endl;
	return 0;
}
輸入一個以數字開頭的表示式,表示式可以包含的運算子有+,-,*,/,^;以回車鍵結束輸入

相關推薦

堆疊表示式

#include<cmath> #include<iostream> #include<stack> #include<algorithm> #include<stdexcept> #include<stri

C++字尾表示式(逆波蘭)四則表示式,採用STL中的stack

簡介: 20 世紀50 年代, 波蘭邏輯學家JanLukasiewicz ,想到了一種不需要括號的字尾表達法,我們也把它稱為逆波蘭( Reverse Polish Notation, RPN) 表示,對於"如9 + (3 -1 ) X3 +10-/2 " ,如果要用字尾表示

《資料結構》嚴蔚敏 演算法3.4 棧實現表示式

emmmm 我又偷懶了,看了一下書上的演算法,總感覺不是很好的演算法,我覺得可以類比前面的符號匹配來進行表示式求值,但是今天有點不想寫了,先copy一個答案吧 原文連結:https://blog.csdn.net/hello_sheep/article/details/75635777

棧進行表示式

先簡單地闡述一下運算子的3個規則: ①先乘方、開方,再乘、除,最後才是加、減; ②從左到右運算 ③有括號得先算括號裡的,再算括號外的。 對於字元一個一個地 getchar(),如果這個字元是數字的話,那麼就將其壓入資料棧,如果是運算子那麼就壓入算符棧

利用堆疊進行表示式的方法(一)

開發十年,就只剩下這套架構體系了! >>>   

利用堆疊進行表示式的方法(二)

開發十年,就只剩下這套架構體系了! >>>   

c# 正則表示式獲取開始和結束字串中間的

/// <summary> /// 獲得字串中開始和結束字串中間得值 /// </summary> /// <param name="str">字串</param> /// <param name="s">開始</param>

正則表示式提取Cookie

Cookie是以“;”進行分隔的鍵值對字串,因此如果要提取所以的鍵值,我們需要對字串進行“;”與“=”的split(分割)操作,如下: function initCookie() { var cookie = document.cookie,

利用棧表示式,可供小學生作業,並能給出分數

設計一個系統,能夠計算使用者輸入的代數表示式(混合四則運算),並能接收使用者自己輸入的運算結果同時給出使用者計算正確與否的判斷,具體要求如下: 1.使用者迴圈輸入不通的算術表示式(每個表示式以“#”結束),程式利用棧求解各個表示式的值; 2.程式每計算完一個表示式,就要求使

Mssql中實現正則表示式更新欄位

create   function   dbo.regexReplace     (     @source   varchar(5000),         --原字串     @regexp   varchar(1000),         --正則表示式     @replace   varch

背景下動態刪除線段樹節點

int scan 輸入 包含 mes else 兩個 let del 動態最值(minmax.Cpp/c/Java)(空間限制128M)有一個包含n個元素的數組,要求實現以下操作:DELETE k:刪除位置k上的數。右邊的數往左移一個位置。QUERY i j:查詢位置i~j

HDU - 1754 I Hate It (線段樹區間)

clas lan () esp tdi typedef show scanf ons 題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1754 題意:線段樹的單點更新和區間求最值 模板題,,,???,, 1 #in

√n歐拉函數

.... n) png pan spa height num 線性 idt 基本定理: 首先看一下核心代碼: 核心代碼 原理解析: 當初我看不懂這段代碼,主要有這麽幾個問題: 1.定理裏面不是一開始寫了一個n*xxx麽?為什麽代碼裏

RMQ

優先 元素 避免 min 轉移 query 代碼 意義 區間樹 1. 概述 RMQ(Range Minimum/Maximum Query),即區間最值查詢,是指這樣一個問題:對於長度為n的數列A,回答若幹詢問RMQ(A,i,j)(i,j<=n),返回數列A中下標在i

ulimit調優|設置普通戶的ulimit

調優 ulimit 個人總結:如何設置普通用戶的ulimit值1、vim /etc/profile增加 ulimit -n 10240source /etc/profile 重新啟動就不需要運行這個命令了。2、修改/etc/security/limits.conf增加* hard n

c++中賦運算符重載為什麽要引用做返回?

font round opera () const pub copy構造函數 per size class string{ public: string(const char *str=NULL); string(const string& str);

5個數

color nbsp pro 數據 display log c語言 五個 描述 http://acm.nyist.net/JudgeOnline/problem.php?pid=31 c語言書上的題目 描述設計一個從5個整數中取最小數和最大數的程序輸入輸入只有一組測試數據,

1156π的

namespace while 問題 strong pre clu pow using 代碼 1 #include<cstdio> 2 #include<cmath> 3 using namespace std; 4 double at(d

Gson按照鍵key排序json所有節點

span urn ive exception tree 8.0 ring creat entryset <dependency> <groupId>commons-io</groupId> <artifactId&

filter素數

一個 else 素數 個數 IT return rime prime prim 1 def _odd_iter(): 2 n = 1 3 while True: 4 n = n+2 5 yield n 6