📄 expressioncalculator.cpp
字号:
// ExpressionCalculator.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int Compute(int l,int r,const char& c)
{
if(c == '-')
return r - l;
if(c == '+')
return l + r;
if(c == '*')
return l * r;
if(c == '/')
{
if(r == 0)
throw string("Denominator cannot be zero value");
else
return l / r;
}
}
void StackOperator(stack<int>& Operand,stack<char>& Operator)
{
int r,lside,rside;
rside = Operand.top();
Operand.pop();
lside = Operand.top();
Operand.pop();
r = Compute(lside,rside,Operator.top());
Operator.pop();
Operand.push(r);
}
int Calculator(const string& Expression)
{
int num = 0,result = 0;
char c;
stack<char> Operator,SOperator;
stack<int> Operand,SOperand;
for(int i = 0; i < Expression.length(); i++)
{
c = Expression[i];
if( c >= '0' && c <= '9')
{
num = num * 10 + c - '0';
if(i != Expression.length() - 1)
{
if(Expression[i+1] > '9' || Expression[i+1] < '0')
Operand.push(num);
}
else
{
Operand.push(num);
}
}
else if( c == ')')
{
StackOperator(Operand,Operator);
}
else if(c == '+'|| c == '-'|| c == '*'|| c == '/')
{
num = 0;
Operator.push(c);
}
}
while(!Operator.empty())
{
if(Operator.top() == '+' || Operator.top() == '-')
{
SOperator.push(Operator.top());
SOperand.push(Operand.top());
Operator.pop();
Operand.pop();
}
else
{
StackOperator(Operand,Operator);
}
}
SOperand.push(Operand.top());
Operand.pop();
while(!SOperator.empty())
{
StackOperator(SOperand,SOperator);
}
return SOperand.top();
}
int _tmain(int argc, _TCHAR* argv[])
{
string Expression;
int result;
getline(cin , Expression , '\n');
try{
cout<<Calculator(Expression)<<endl;
}
catch(const string& msg)
{
cout<<msg<<endl;
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -