簡單計算器 九度教程第27題 用棧模擬計算器的模板題

題目鏈接

讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
輸入描述:
測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
輸出描述:
對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
示例1
輸入
1 + 2
4 + 2 * 5 - 7 / 11
0
輸出
3.00
13.36

解題思路:
具體思路可以參見我的上一篇博客:
CCF 201903-2 二十四點 用棧模擬簡單計算器
這一題中有一個不同點是表達式中的數字不再侷限於個位數,因此碰到數字時要求出完整的數字大小。

int now = 0;
while (i < len&&str[i] >= '0'&&str[i] <= '9') {
	now = now * 10 + str[i] - '0';
    i++;
}
//在本題目中 由於有空格的存在 因此無需這一步  但如果表達式中沒有多餘的空格,就不能省去這一步
//i -= 1;

AC代碼:

#include<iostream>
#include<stack>
#include<stdio.h>
#include<string.h>
using namespace std;
stack<double> num;
stack<char> s;
char str[205];
int main() {
	while (gets(str)) {
		int len = strlen(str);
		if (len == 1 && str[0] == '0') break;
		if (!num.empty())num.pop();
		if (!s.empty())s.pop();
		double a, b; char op;
		for (int i = 0; i < len; i++) {
			if (str[i] == ' ')continue;
			if (str[i] >= '0' && str[i] <= '9') {//如果是操作數
				int now = 0;
				while (i < len&&str[i] >= '0'&&str[i] <= '9') {
					now = now * 10 + str[i] - '0';
					i++;
				}
				//在本題目中 由於有空格的存在 因此無需這一步  但如果表達式中沒有多餘的空格,就不能省去這一步
				//i -= 1;
				if (!s.empty() && s.top() == '-') {//對減法適當處理
					num.push(now*(-1));
				}
				else num.push(now);
				if (!s.empty() && (s.top() == '*' || s.top() == '/')) {//乘法和除法則直接計算
					b = num.top(); num.pop();
					a = num.top(); num.pop();
					op = s.top(); s.pop();
					if (op == '*')num.push(a*b);
					else num.push(a / b);
				}
			}
			else s.push(str[i]);
		}
		while (!s.empty()) {
			b = num.top(); num.pop();
			a = num.top(); num.pop();
			s.pop();
			num.push(a + b);
		}
		double tmp = num.top(); num.pop();
		printf("%.2f\n", tmp);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章