计算器源代码

源代码is:

就发绿卡的数据分类开撒就发绿卡的撒就分厘卡电视机分厘卡就的萨芬里卡多解放了

#include<iostream>
#include<string>
#include<stack>
using namespace std;
 
void calculator(string str) {
	string::iterator it = str.begin();//迭代器
	stack<char> s1;//s1是用来存放运算符的栈
	stack<int> s2;//s3是用来存放数字的栈
	while (it != str.end()) {
		//运算符优先级:) > *、/、% > +、- > ( 且 ( 特例,直接入栈
		if (*it == '+' || *it == '-' || *it == '*' || *it == '/' || *it == '%' || *it == '(') {
			//当遇到栈顶为 *、/、% 读取的字符为 +、- 时,即读取的运算符优先级低于符号栈顶元素优先级 
			//或
			//当遇到栈顶为 *、/、% 读取的字符为*、/、%时,即读取的运算符优先级等于符号栈顶元素优先级时
			if (!s1.empty() && (s1.top() == '*' || s1.top() == '/' || s1.top() == '%') && *it != '(') {//注意这里要加上栈判空,否则会导致开始的时候出错
				int num2 = s2.top();
				s2.pop();
				int num1 = s2.top();
				s2.pop();
				if (s1.top() == '*') {
					s2.push(num1 * num2);
				}
				else if (s1.top() == '/') {
					s2.push(num1 / num2);
				}
				else {
					s2.push(num1 % num2);
				}
				s1.pop();
				s1.push(*it);
			}
			//当遇到栈顶为 +、- 读取的字符为 +、- 时,即读取的运算符优先级等于符号栈顶元素优先级
			else if (!s1.empty() && (s1.top() == '+' || s1.top() == '-') && (*it == '+' || *it == '-')) {//注意这里要在前面加栈的判空,否则会导致开始的时候出错
				int num2 = s2.top();
				s2.pop();
				int num1 = s2.top();
				s2.pop();
				if (s1.top() == '+') {
					s2.push(num1 + num2);
				}
				else {
					s2.push(num1 - num2);
				}
				s1.pop();
				s1.push(*it);
			}
			//当遇到栈顶为 +、- 读取的字符为 *、/、% 时,即读取的运算符优先级高于符号栈顶元素优先级
			//或
			//当遇到栈顶为 ( 读取的字符为 +、-、 *、/、% 时,即读取的运算符优先级高于符号栈顶元素优先级
			//或
			//读取的字符为 ( 时
			else {
				s1.push(*it);
			}
		}
		else if (*it == ')') {//匹配到右括号
			while (s1.top() != '(') {
				int num2 = s2.top();
				s2.pop();
				int num1 = s2.top();
				s2.pop();
				if (s1.top() == '+') {
					s2.push(num1 + num2);
				}
				else if (s1.top() == '-') {
					s2.push(num1 - num2);
				}
				else if (s1.top() == '*') {
					s2.push(num1 * num2);
				}
				else if (s1.top() == '/') {
					s2.push(num1 / num2);
				}
				else {
					s2.push(num1 % num2);
				}
				s1.pop();
			}
			s1.pop();
		}
		else {//匹配到数字
			s2.push((int)(*it-'0'));//转换为整型
		}
		it++;
	}
 
	//还差一步
	int num2 = s2.top();
	s2.pop();
	int num1 = s2.top();
	s2.pop();
	if (s1.top() == '+') {
		s2.push(num1 + num2);
	}
	else if (s1.top() == '-') {
		s2.push(num1 - num2);
	}
	else if (s1.top() == '*') {
		s2.push(num1 * num2);
	}
	else if (s1.top() == '/') {
		s2.push(num1 / num2);
	}
	else {
		s2.push(num1 % num2);
	}
	cout << s2.top() << endl;
}
 
int main() {
	int n;
	n=10000005;
	for(int i=0;i<n;i++)
	{
		string s;
		cin>>s;
		calculator(s);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值