【题目要求】
Implement a calculator program based on a Reverse Polish notation.
【输入】
There could be several lines. Each line contains a Reverse Polish notation. The operators and operands are sepertated by spaces( there could be more than 1 spaces between input tokens).
1 2 3 - + *
1 -
2 0 /
-
1 2 +
2.2 3.25 1.1 2.5 / - 1.32 * +
【输出】
Output result of each test case and keep 4 numbers after the decimal point.
Output ‘ERROR’ if there are errors of the input test case.
ERROR
ERROR
ERROR
ERROR
3.0000
5.9092
【我的程序】
#include <stdio.h>
#include <iostream>
#include <iomanip>
#define maxSize 500
using namespace std;
class myCal
{
private:
int depth;
double a[maxSize];
public:
myCal() { depth=-1; }
void init() { depth=-1; }
int getDepth() { return depth; }
double getData() { return a[depth]; }
void myPush(double t) { a[++depth]=t; }
int myPlus() { if (depth<1) return 1; a[depth-1]+=a[depth]; depth--; return 0; }
int myMinus() { if (depth<1) return 1; a[depth-1]-=a[depth]; depth--; return 0; }
int myMultiple() { if (depth<1) return 1; a[depth-1]*=a[depth]; depth--; return 0; }
int myDivide() { if (depth<1) return 1; if (a[depth]==0) return 1; a[depth-1]/=a[depth]; depth--; return 0; }
};
int main()
{
char ch;
double t;
int flag=0;
myCal my;
cout << fixed << setprecision(4);
do
{
ch=cin.get();
if (ch=='\n')
{
if (flag==0 && my.getDepth()==0) cout<< my.getData() << endl;
else cout<< "ERROR" << endl;
flag=0;
my.init();
}
if ((ch<='9' && ch>='0') || ch=='.') { cin.putback(ch); cin>>t; my.myPush(t); }
if (ch=='+' && flag==0) flag=my.myPlus();
if (ch=='-' && flag==0) flag=my.myMinus();
if (ch=='*' && flag==0) flag=my.myMultiple();
if (ch=='/' && flag==0) flag=my.myDivide();
}while (ch!=EOF);
return 0;
}