简单计算器

在这里插入图片描述
在这里插入图片描述

#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;

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

bool In(string s)
{
	if (s.length() > 1)
	{
		return false;
	}
	else if (s[0] - '0' >= 0 && s[0] - '0' <= 9)
	{
		return false;
	}
	else
		return true;
}

char ope[7][8]={
	{ '=','<','<','<','<','<','<' },
	{ '>','>','>','<','<','<','>' },
	{ '>','>','>','<','<','<','>' },
	{ '>','>','>','>','>','<','>' },
	{ '>','>','>','>','>','<','>' },
	{ '>','<','<','<','<','<','=' },
	{ '>','>','>','>','>','=','>' }
};

int getnum(char c)
{
	switch (c)
	{
	case '#':
		return 0;
	case '+':
		return 1;
	case '-':
		return 2;
	case '*':
		return 3;
	case '/':
		return 4;
	case '(':
		return 5;
	case ')':
		return 6;
	}
}

char Precede(char c, string s)
{
	return ope[getnum(c)][getnum(s[0])];
}

double operate(double d1, char c, double d2)
{
	switch (c)
	{
	case '+':
		return d1 + d2;
	case '-':
		return d2 - d1;
	case '*':
		return d1*d2;
	case '/':
		return d2 / d1;
	}
}

int main()
{
	while (getline(cin,str))
	{
		if (str == "0")
			break;
		vector<string> s;
		int t = 0;
		for (int i = 0; i < str.length(); i++)
		{
			if (str[i] == ' ')
			{
				string ss = str.substr(t, i - t);
				s.push_back(ss);
				t = i + 1;
			}
			else if (i == str.length() - 1)
			{
				string ss = str.substr(t);
				s.push_back(ss);
			}
		}
		s.push_back("#");
		stack<double> num;
		stack<char> op;
		op.push('#');
		int i = 0;
		while(s[i]!="#" || op.top()!='#')
		{
			if (!In(s[i]))
			{
				num.push(atoi(s[i].c_str()));
			}
			else
			{
				char c;
				double d1, d2;
				switch (Precede(op.top(), s[i]))
				{
				case '<':
					op.push(s[i][0]);
					break;
				case '>':
					c = op.top();
					op.pop();
					d1 = num.top();
					num.pop();
					d2 = num.top();
					num.pop();
					num.push(operate(d1, c, d2));
					if(s[i][0]!='#')
					op.push(s[i][0]);
					break;
				case '=':
					op.pop();
					break;
				}
			}
			if(i<s.size()-1)
				i++;
		}
		printf("%.2f\n", num.top());
	}
	return 0;
}

书上代码
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值