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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值