HDU 1237 簡單計算器 (棧的應用)—— C++

讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。

Input
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。

Output
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。

Sample Input

1 + 2
4 + 2 * 5 - 7 / 11
0

Sample Output

3.00
13.36

核心考點:棧的使用。
思路:因爲運算有優先級,所以在剛開始先考慮乘除。
如果當前數字前面的運算符是 “+”,則直接把數壓入棧裏,
如果是減法,則把數的相反數壓入棧裏,
如果是乘法,則取棧頭的數相乘,並 pop() 出棧頭,後把相乘結果 push() 進棧,
除法和乘法方法一樣
代碼

#include <stack>
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main() {
	stack<double>shu;
	string a;
	while (getline(cin,a)&&a!="0") {
		int flag=1,tmp=0;
		for (int i = 0; i < a.length(); i++) {
			if (a[i] == ' ')continue;
			else if (a[i] == '+') flag = 1;
			else if (a[i] == '-') flag = 2;
			else if (a[i] == '*') flag = 3;
			else if (a[i] == '/') flag = 4;
			else{
				tmp = 0;
				while (a[i] >= '0' && a[i] <= '9') {
					tmp = tmp * 10 + (a[i] - '0'); i++;
				}
				i--;
				switch (flag) {
				case 1: shu.push(tmp); break;
				case 2: shu.push(-tmp); break;
				case 3: {
					double x = shu.top() * tmp; shu.pop();
					shu.push(x);
					break;
				}
				case 4: {
					double x = shu.top() / tmp; shu.pop();
					shu.push(x);
					break;
				}
				}
			}
		}
		double ans = 0;
		while (!shu.empty()) {
			ans += shu.top(); shu.pop();
		}
		cout <<setprecision(2)<<fixed<< ans << endl;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章