#include<iostream>
#include<stack>
using namespace std ;
void Compute(stack<double> &double_Stk , stack<char> &char_Stk , char ch) //计算
{
double temp_Double1 ;
double result = 0.00 ;
double temp_Double2 ;
temp_Double1 = double_Stk.top() ;
double_Stk.pop() ;
temp_Double2 = double_Stk.top() ;
double_Stk.pop() ;
switch(ch)
{
case '+':
{
result = temp_Double2 + temp_Double1 ;
double_Stk.push(result) ;
}
break ;
case '-':
{
result = temp_Double2 - temp_Double1 ;
double_Stk.push(result) ;
}
break;
case '*':
{
result = temp_Double2 * temp_Double1 ;
double_Stk.push(result) ;
}
break ;
case '/':
{
result = temp_Double2/temp_Double1 ;
double_Stk.push(result) ;
}
break;
default:
break ;
}
}
double Compute_Exp(const char str[200])
{
const int MAX_SIZE_STRING = 255 ;
char Priority[MAX_SIZE_STRING] ;
stack<double>double_Stk ;
stack<char>char_Stk ;
char temp_Char ;
double result = 0.00 ;
double_Stk.push(-1) ;
char_Stk.push('#') ;
Priority['#'] = '0' ;
Priority['+'] = '1' ;
Priority['-'] = '1' ;
Priority['*'] = '2' ;
Priority['/'] = '2' ;
double temp_Double = 0.00 ;
for(int i = 0 ; str[i] != '\0' ; ++i)
{
if(str[i] >= '0' && str[i] <= '9')
{
temp_Double = temp_Double*10 + (str[i] - '0');
if(str[i+1] == ' ' || str[i+1] == '\0')
{
double_Stk.push(temp_Double) ;
}
}
else if(str[i] == ' ' )
{
temp_Double = 0.00;
}
else
{
temp_Char = char_Stk.top() ;
if(Priority[str[i]] > Priority[temp_Char])
{
char_Stk.push(str[i]) ;
}
else if(Priority[str[i]] == Priority[temp_Char])
{
temp_Char = char_Stk.top() ;
char_Stk.pop() ;
char_Stk.push(str[i]) ;
Compute(double_Stk , char_Stk , temp_Char) ;
}
else
{
Compute(double_Stk , char_Stk , temp_Char) ;
char_Stk.pop() ;
temp_Char = char_Stk.top() ;
if(temp_Char != '#' )
{
Compute(double_Stk , char_Stk , temp_Char) ;
char_Stk.pop() ;
char_Stk.push(str[i]) ;
}
else
{
char_Stk.push(str[i]) ;
}
}
}
}
while(double_Stk.top() != -1 && char_Stk.top() != '#')
{
temp_Char = char_Stk.top() ;
char_Stk.pop() ;
Compute(double_Stk , char_Stk , temp_Char) ;
}
result = double_Stk.top() ;
double_Stk.pop() ;
double_Stk.pop() ;
char_Stk.pop() ;
return result ;
}
int Strlength(char str[200] )
{
int i = 0 ;
for(i = 0 ; str[i] != '\0' ; )
{
++i ;
}
if( i != 0 )
{
return i ;
}
else
{
return 0 ;
}
}
int main(void)
{
char *str = new char[200] ;
cin.getline(str , 200 , '\n') ;
double result = 0.00 ;
int len = Strlength(str) ;
while(true)
{
if(len == 1 )
{
if(str[0] != '0')
{
result = Compute_Exp(str) ;
printf("%.2lf\n" , result) ;
delete [] str ;
str = NULL ;
str = new char[200] ;
cin.getline(str , 200 , '\n') ;
len = Strlength(str) ;
}
else
{
delete [] str ;
break ;
}
}
else
{
result = Compute_Exp(str) ;
printf("%.2lf\n" , result ) ;
delete [] str ;
str = NULL ;
str = new char[200] ;
cin.getline(str , 200 , '\n') ;
len = Strlength(str) ;
}
}
return 0 ;
}
利用栈求表达式的值
最新推荐文章于 2023-07-23 19:54:34 发布