问题 A: 简单计算器

这段代码实现了一个C++程序,用于解析并计算中缀表达式。它使用栈和队列数据结构,遵循运算符优先级进行计算,支持加、减、乘、除四种基本运算。程序首先将中缀表达式转换为后缀表达式,然后进行计算,最后输出结果。
摘要由CSDN通过智能技术生成

在这里插入图片描述

#include <cstdio>
#include <string>
#include <iostream>
#include <stack>
#include <queue>
#include <map>

using namespace std;

bool isop(char c){
	if(c=='+' || c=='*' || c=='-' || c=='/') return true;
	return false;
}

struct Node{
	double num;
	char op;
	bool flag;
};

stack<Node> st;
queue<Node> q;
map<char,int> m;
string str;

void change(){
	Node node;
	
	for(int i=0; i<str.size();){
		if(str[i]<='9' && str[i]>='0'){
			node.flag = 1;
			node.num = str[i] - '0';
			i++;
			
			while(i<str.size() && str[i]<='9' && str[i]>='0'){
				node.num = node.num*10 + (str[i]-'0');
				i++;
			}
			q.push(node);
		}else{
			node.flag = 0;
			node.op = str[i];
			
			while(!st.empty() && m[node.op]<=m[st.top().op]){
				q.push(st.top());
				st.pop();
			}
			st.push(node);
			i++;
		}
	}
	while(!st.empty()){
		q.push(st.top());
		st.pop();
	}
}

double cal(){
	double temp1;
	double temp2;
	Node res;
	res.flag = 1;
	while(!q.empty()){
		Node node = q.front();
		q.pop();
		if(node.flag){
			st.push(node);
		}else{
			temp2 = st.top().num;
			st.pop();
			temp1 = st.top().num;
			st.pop();
			if(node.op == '+'){
				res.num = temp1 + temp2;
			}else if(node.op == '-'){
				res.num = temp1 - temp2;
			}else if(node.op == '*'){
				res.num = temp1 * temp2;
			}else if(node.op == '/'){
				res.num = temp1 / temp2;
			}
			st.push(res);
		}
	}
	return st.top().num;
}

int main(){
	m['-'] = 0;
	m['+'] = 0;
	m['*'] = 1;
	m['/'] = 1;
	
	
	while(getline(cin, str), str!="0"){
		for(string::iterator it=str.begin(); it!=str.end(); it++){
			if(*it == ' ') str.erase(it);
		}
		while(!st.empty()){
			st.pop();
		}
		change();
//		while(!q.empty()){
//			if(q.front().flag){
//				printf("%.0f", q.front().num);
//			}else{
//				printf("%c", q.front().op);
//			}
//			q.pop();
//		}
		printf("%.2f\n", cal());
	}
	
	return 0;
}

写了好久,好难好难好难QAQ

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值