闲来没事的时候写了个算术表达式求值的程序,还不够完善…估计也没有时间去完善了。
用的是中缀表达式转后缀表达式,另外还有的方法是用二叉树。
/*??????????????????????????????????????????????????????????????????*/
#ifndef __ARITHMETIC_EXPRESSION_H
#define __ARITHMETIC_EXPRESSION_H
namespace dskit
{#define MAXLENEXPRESSION 100
class ArithmeticExpression
{public:
ArithmeticExpression(const char* expression);
int Compute();
bool IsValidate();
private:
void ConvertToSuffix();
int Priority(char a, char b);
private:
char m_data[MAXLENEXPRESSION];
};
}
#endif
#include
#include
#include "arithmetic_expression.h"
#include "stack.h"
dskit::ArithmeticExpression::ArithmeticExpression(const char* expression)
{strcpy(m_data, expression);
}
int dskit::ArithmeticExpression::Compute()
{ConvertToSuffix();
//Stack s = CreateStack(MAXLENEXPRESSION);
//DisposeStack(s);
return 0;
}
bool dskit::ArithmeticExpression::IsValidate()
{return false;
}
/*Is a priority b*/
int dskit::ArithmeticExpression::Priority(char a, char b)
{if( ('(' == a && ')' == b) || ('(' == b && ')' == a) )return 0;
if( ('+' == a && '-' == b) || ('-' == b && '+' == a) )return 0;
if( ('*' == a && '/' == b) || ('/' == b && '*' == a) )return 0;
if( ('*' == a || '/' == a) && ('+' == b || '-' == b) )return 1;
if( ('(' == a || ')' == a) && ('+' == b || '-' == b) )return 1;
if( ('(' == a || ')' == a) && ('*' == b || '/' == b) )return 1;
return -1;
}
void dskit::ArithmeticExpression::ConvertToSuffix()
{char p[MAXLENEXPRESSION];
Stack s = CreateStack(MAXLENEXPRESSION);
size_t index = 0;
char* pTemp = m_data;
for(; '/0' != *pTemp; ++pTemp)
{if(*pTemp != ' ')
{if('(' == *pTemp || ')' == *pTemp || '+' == *pTemp || '-' == *pTemp || '*' == *pTemp || '/' == *pTemp){if(IsEmpty(s) || '(' == *pTemp){Push(*pTemp, s);
continue;
}
if(')' == *pTemp){while(!IsEmpty(s) && Top(s) != '('){p[index++] = Pop(s);
}
if(!IsEmpty(s)) Pop(s);
continue;
}
int iPriority = Priority(*pTemp, Top(s));
if(iPriority <= 0)
{p[index++] = Pop(s);
while(!IsEmpty(s))
{iPriority = Priority(*pTemp, Top(s));
if(iPriority <= 0)
{p[index++] = Pop(s);
}
else
break;
}
}
Push(*pTemp, s);
}
else
{p[index++] = *pTemp;
}
}//end of if
}//end of for
while(!IsEmpty(s))
if(Top(s) != '(') p[index++] = Pop(s);p[index] = '/0';
//strcpy(p, m_data);
DisposeStack(s);
std::cout << p << std::endl;
}
int main(int argc, char* argv[])
{dskit::ArithmeticExpression ae("1+2*3/4-8+5*7");ae.Compute();
return 0;
}
930

被折叠的 条评论
为什么被折叠?



