正整数的四则混合运算
表达式合法字符有
0...9 + - * / ( ) =
必须以 = 结尾
应用举例
...
char exp[] = "((1+2)*3-4+5*6)/7=";
double result;
if( expression( exp , result ) )
{
cout<<"result="<<result<<endl;
}
else
{
cout<<"表达式有错"<<endl;
}
...
////////////////////////////////////////////////////////////
// 功能:正整数四则运算求值
// 时间:12:23 2005-10-2
// 最后修改时间:12:24 2005-10-2
////////////////////////////////////////////////////////////
#include "iostream.h"
#define max 1024
void solve( double num1 , double num2 , char op , double &ret )
{
switch( op )
{
case '+':
ret = num1 + num2;
break;
case '-':
ret = num1 - num2;
break;
case '*':
ret = num1 * num2;
break;
case '/':
if( num2 != 0 )
ret = num1 / num2;
break;
}
}
bool expression( char exp[] , double &ret )
{
//操作符栈
char opStack[max];
int opTop = 0;
//操作数栈
double numStack[max];
int numTop = 0;
//记录两数的运算结果
double result = 0;
double num1;
double num2;
char op;
//读入表达式的字符
char ch;
//表达式当前的字符指针
int p = 0;
//构造数字时用到
double t;
opStack[0] = '#';
opTop = 1;
ch = exp[p++];
while( ch != '=' )
{
if( ch >= '0' && ch <= '9' )
{
//读入数字
t = 0;
while( ch >= '0' && ch <= '9' )
{
t = 10 * t + ( ch - '0' );
ch = exp[p++];
}
numStack[numTop++] = t;
}
else if( ch == '(' )
{
opStack[opTop++] = ch;
ch = exp[p++];
}
else if( ch == ')' )
{
//每次运算前检查是否有足够的操作数及操作符
if( numTop <= 1 || opTop <= 1 )
return false;
num2 = numStack[--numTop];
num1 = numStack[--numTop];
op = opStack[--opTop];
solve( num1 , num2 , op , result );
numStack[numTop++] = result;
//括号不匹配
if( opStack[--opTop] != '(' )
return false;
ch = exp[p++];
}
else if( ( ch == '+' || ch == '-' )
&& opStack[opTop-1] != '('
&& opStack[opTop-1] != '#' )
{
if( numTop <= 1 || opTop <= 1 )
return false;
num2 = numStack[--numTop];
num1 = numStack[--numTop];
op = opStack[--opTop];
solve( num1 , num2 , op , result );
numStack[numTop++] = result;
}
else if( ( ch == '*' || ch == '/' )
&& ( opStack[opTop-1] == '+'
|| opStack[opTop-1] == '-' ) )
{
opStack[opTop++] = ch;
ch = exp[p++];
}
else if( ( ch == '*' || ch == '/' )
&& ( opStack[opTop-1] == '*'
|| opStack[opTop-1] == '/' ) )
{
if( numTop <= 1 || opTop <= 1 )
return false;
num2 = numStack[--numTop];
num1 = numStack[--numTop];
op = opStack[--opTop];
solve( num1 , num2 , op , result );
numStack[numTop++] = result;
}
else
{
opStack[opTop++] = ch;
ch = exp[p++];
}
}
if( numTop <= 1 || opTop <= 1 )
return false;
num2 = numStack[--numTop];
num1 = numStack[--numTop];
op = opStack[--opTop];
solve( num1 , num2 , op , result );
numStack[numTop++] = result;
ret = numStack[numTop-1];
return true;
}
void main()
{
char exp[] = "((1+2)*3-4+5*6)/7=";
double ret;
if( expression( exp , ret ) )
cout<<"ret="<<ret<<endl;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////