题解 | #简单计算器#

简单计算器

https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130

#include <iostream>
#include <stack>
#include <string>
using namespace std;

stack<double> num;
stack<char> op;
string post;

void init() {
	while (!op.empty()) op.pop();
	while (!num.empty()) num.pop();
	post.clear();
}

int pre(char op) {
	if (op == '+' || op == '-') return 1;
	if (op == '*' || op == '/') return 2;
	return 0;
}

void eval() {
	double r = num.top();
	num.pop();
	double l = num.top();
	num.pop();
	char opcode = op.top();
	op.pop();
	post += opcode;
	if (opcode == '+') num.push(l + r);
	if (opcode == '-') num.push(l - r);
	if (opcode == '*') num.push(l * r);
	if (opcode == '/') num.push(l / r);
}

int main() {
	// freopen("input.txt", "r", stdin);
	string s;
	while (getline(cin, s)) {
		if (s == "0") break;
		init();
		for (int i = 0; i < s.size(); i++) {
			if (isspace(s[i])) continue;
			if (isdigit(s[i])) {
				double t = 0;
				while (i < s.size() && isdigit(s[i])) {
					post += s[i];
					t = t * 10 + s[i++] - '0';
				}
				i--;
				num.push(t);
			} else if (s[i] == '(') op.push(s[i]);
			else if (s[i] == ')') {
				while (!op.empty() && op.top() != '(') {
					eval();
				}
				op.pop();
			} else {
				while (!op.empty() && pre(op.top()) >= pre(s[i])) {
					eval();
				}
				op.push(s[i]);
			}
		}
		while (!op.empty()) {
			eval();
		}

//		printf("%c", post[0]);
//		for (int i = 1; i < post.size(); i++) {
//			printf(" %c", post[i]);
//		}
//		puts("");
		printf("%.2lf\n", num.top());
	}
	return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务