有点乱,楼主见谅
//stack.h
#ifndef __STACK__
#define __STACK__
template<class T>
class Stack
{
private:
T stack[100];
int top;
public:
Stack();
~Stack(){}
T pop();
void push(T);
T get();
int length();
};
template<class T> Stack<T>::Stack()
{
top=-1;
}
template<class T> T Stack<T>::pop()
{
T temp;
if(top>0)
{
temp=stack[top];
top--;
}
else
return 0;
return temp;
}
template<class T> void Stack<T>::push(T c)
{
if(top<=99)
{
top++;
stack[top]=c;
}
else
cout<<"up range over"<<endl;
}
template<class T> T Stack<T>::get()
{
if(top>=0)
return stack[top];
else
{
cout<<"over range"<<endl;
return 0;
}
}
template<class T> int Stack<T>::length()
{
return top;
}
#endif
//function.cpp
#include<iostream>
#include<string>
using namespace std;
#include "stack.h"
char opchar[]={'(',')','+','-','*','/'};
int priority(char c,Stack<char>& op)//返回运算符的优先性
{
int i=0;
int m=-1,n=-1;
while(i<6)
{
if(m!=-1&&n!=-1)
break;
if(c==opchar[i])
m=i;
if(op.get()==opchar[i])
n=i;
i++;
}
return m-n;
}
void count(Stack<float>& num,char c)//计算
{
float temp=num.pop();
switch(c)
{
case '+':
temp+=num.pop();
break;
case '-':
temp=num.pop()-temp;
break;
case '*':
temp*=num.pop();
break;
case '/':
temp=num.pop()/temp;
break;
default:
return;
}
num.push(temp);
}
float get_n(const char *& p)//取数
{
int t=0;
float temp=0;
while(*p>='0'&&*p<='9')
{
temp=temp*10+(*p-'0');
p++;
}
if(*p=='.')
p++;
while(*p>='0'&&*p<='9')
{
int i;
float m=*p-'0';
for(i=0;i<=t;i++)
m/=10;
temp+=m;
t++;
p++;
}
return temp;
}
char get_c(const char *& p)//字符取词
{
char c='\0';
if(*p=='+')
c='+';
else if(*p=='-')
c='-';
else if(*p=='*')
c='*';
else if(*p=='/')
c='/';
else if(*p=='(')
c='(';
else if(*p==')')
c=')';
else
cout<<"unknown char!"<<endl;
p++;
return c;
}
void token(const char * s,Stack<float>& num,Stack<char>& op)//取词
{
const char *p=s;
float temp=0;
char c;
while(*p!='\0')
{
while(*p=='(')
{
op.push(*p);
p++;
}
if(*p=='-')
{
op.push('-');
num.push(0);
p++;
continue;
}
if(*p>='0'&&*p<='9')
{
temp=get_n(p);
num.push(temp);
}
if(*p=='\0')
break;
else
{
c=get_c(p);
if(c==')')
{
while(priority(c,op)<0)
count(num,op.pop());
if(priority(c,op)==1)
{
op.pop();
if(*p!='\0')
c=get_c(p);
else
break;
}
else
cout<<"no '(' match ')'"<<endl;
}
while(priority(c,op)<=0)
count(num,op.pop());
op.push(c);
}
}
}
//main.cpp
#include<iostream>
#include<string>
using namespace std;
#include"stack.h"
int main()
{
char s[100];
char *p;
Stack<float> num;
Stack<char> op;
extern int priority(char,Stack<char>&);
void count(Stack<float>&,char);
float get_n(const char *&);
char get_c(const char *&);
void token(const char*,Stack<float>&,Stack<char>&);
num.push(0);
op.push('(');
cout<<"
按
Ctrl+Z
退出"<<endl;
cout<<"please enter your expression:"<<endl;
while(cin>>s)
{
p=s;
token(p,num,op);
while(op.length()>0)
count(num,op.pop());
cout<<"="<<num.get()<<endl;
}
return 0;
}