Jobdu 题目1019:简单计算器

http://ac.jobdu.com/problem.php?pid=1019

题目描述:
    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
    测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
    对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 2
4 + 2 * 5 - 7 / 11
0
样例输出:
3.00
13.36
#include <cstdio>
double s[200];
int main(){
	double x;
	char ch;
	while (scanf("%lf", &x) != EOF){
		scanf("%c", &ch);
		if (x == 0 && ch == '\n') break;
		int i = 0;
		s[i] = x;
		while (scanf("%c %lf", &ch, &x) != EOF){
			if (ch == '+')
				s[++i] = x;
			else if (ch == '-')
				s[++i] = -x;
			else if (ch == '*')
				s[i] *= x;
			else if (ch == '/')
				s[i] /= x;
			if (getchar() == '\n') break;
		}
		double sum = 0;
		for (; i >= 0; i--)
			sum += s[i];
		printf("%.2lf\n", sum);
	}
	return 0;
}


建立运算数栈和运算符栈的解法:

#include <iostream>
#include <cstdio>
#include <sstream>
#include <stack>
using namespace std;

double cal(double a, char op, double b){
	switch (op){
		case '+':
			return a + b;
		case '-':
			return a - b;
		case '*':
			return a * b;
		case '/':
			return a / b;
	}
}

int main(){
	string str;
	char op;
	double a, b;
	while (getline(cin, str) && str != "0"){
		stack<double> s1;
		stack<char> s2;
		stringstream ss(str);
		ss >> a;
		s1.push(a);
		while (ss >> op){
			if (op == '*' || op == '/'){
				a = s1.top();
				s1.pop();
				ss >> b;
				s1.push(cal(a, op, b));
			}
			else{
				while (!s2.empty()){
					char op1 = s2.top();
					s2.pop();
					b = s1.top();
					s1.pop();
					a = s1.top();
					s1.pop();
					s1.push(cal(a, op1, b));
				}
				ss >> b;
				s2.push(op);
				s1.push(b);
			}
		}
		while (!s2.empty()){
			char op = s2.top();
			s2.pop();
			b = s1.top();
			s1.pop();
			a = s1.top();
			s1.pop();
			s1.push(cal(a, op, b));
		}
		printf("%.2lf\n", s1.top());
	}
	return 0;
}



你可能感兴趣的:(Jobdu 题目1019:简单计算器)