exam3.cpp
来自「C++语言程序设计题典」· C++ 代码 · 共 149 行
CPP
149 行
#include <iostream.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
const int Max=20;
class Stack
{
double stack[Max];
int top;
public:
Stack() { top=-1; }
void push(double d)
{
if (top==Max-1)
{
cout << "栈上溢出" << endl;
return;
}
top++;
stack[top]=d;
}
double pop()
{
double temp;
if (top==-1)
{
cout << "栈下溢出" << endl;
exit(1);
}
temp=stack[top];
top--;
return temp;
}
void clear()
{
top=-1;
}
double peek()
{
if (top==-1)
{
cout << "栈下溢出" << endl;
exit(1);
}
return stack[top];
}
int empty()
{
return (top==-1);
}
int full()
{
return (top==Max-1);
}
};
class Calc
{
Stack S;
void enter(double d)
{
S.push(d);
}
int gettwodata(double &op1,double &op2)
{
if (S.empty())
{
cout << "没有操作数" << endl;
return 0;
}
op1=S.pop();
if (S.empty())
{
cout << "操作数不够" << endl;
return 0;
}
op2=S.pop();
return 1;
}
void computer(char op)
{
int result;
double op1,op2;
result=gettwodata(op1,op2);
if (result==1)
{
switch(op)
{
case '+':S.push(op2+op1);
break;
case '-':S.push(op2-op1);
break;
case '*':S.push(op2*op1);
break;
case '/':if (op1==0)
{
cout << "除零错误" << endl;
S.clear();
}
else
S.push(op2/op1);
break;
case '^':S.push(pow(op2,op1));
break;
}
cout << " >>" << S.peek() << " ";
}
else
S.clear();
}
public:
Calc() {};
void run()
{
char c[20];
while (1)
{
cin >> c;
if (*c=='q') break; //键入q表示退出
switch (*c)
{
case 'c':S.clear(); //键入c表示从新开始计算
break;
case '-':if (strlen(c)>1)
enter(atof(c));
else
computer(*c);
break;
case '+':
case '*':
case '/':
case '^':computer(*c);
break;
default:enter(atof(c));
break;
}
}
}
void clear()
{
S.clear();
}
};
void main()
{
cout << "输入后缀表达式(数,符号,数之间空一格):\n >>";
Calc c;
c.run();
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?