c++简单计算器

问题 C: 某计算器的超电磁炮

时间限制: 1 Sec
内存限制: 64 MB

题目描述

输入由非负整数、+、-、*、/、(、)组成的计算表达式,计算该表达式的值。

输入

每个输入文件中一组数据。

输入只有一行,不超过200个字符,其中不存在空格。数据保证表达式一定合法,且所有的整数都不小于0、不大于1024。中间结果保证不超过15位有效数位精度。

输出

输出一行,即表达式的值,结果精度保留小数点后2位。

样例输入

3+(12/(2*2+1))

样例输出

5.40

这道题其实是大一下学期学C++的时候上机的一道题,今晚练习赛写了一个钟多,没能AC,参考了一下以前的代码,感慨自己脑力确实不如从前了,也说不定自己四年从来都没强过。好吧,后天机试,学渣继续加油~

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#include <algorithm>
#include <stack>
#include <cstring>
#include <set>
#include <map>
using namespace std;

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

bool valid(char c) {
    if (op.empty())
        return false;
    if (op.top() == '(')
        return false;
    if (c == '+' || c == '-')
        return true;
    if (c == '*' && (op.top() == '*' || op.top() == '/'))
        return true;
    if (c == '/' && (op.top() == '*' || op.top() == '/'))
        return true;
    else
        return false;
}

void exe() {
    double result;
    double b = num.top();
    num.pop();
    double a = num.top();
    num.pop();
    char c = op.top();
    op.pop();
    switch (c) {
    case '+':
        result = a + b;
        break;
    case '-':
        result = a - b;
        break;
    case '*':
        result = a * b;
        break;
    case '/':
        result = a / b;
        break;
    }
    num.push(result);
}

int main() {
	string str;
	cin >> str;
	int temp = 0;
	for (int i = 0; i < str.length(); i++) {
		if (str[i] >= '0' && str[i] <= '9') {
			temp = temp * 10 + str[i] - '0';
			if (i + 1 == str.length() || !(str[i + 1] >= '0' && str[i + 1] <= '9')) {
				num.push(temp);
				temp = 0;
			}
		} else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
			while (valid(str[i])) {
				exe();
			}
			op.push(str[i]);
		} else if (str[i] == '(') {
			op.push('(');
		} else if (str[i] == ')') {
			while (op.top() != '(') {
				exe();
			}
			op.pop();
		}
	}
	printf("%.2lf\n", num.top());
	return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值