目前,我正在制作一个输入数学表达式的计算器,并使用RPn来计算它。因此,我使用一个中缀到postfix转换器函数来转换它。计算器通过将数字推入堆栈并检测运算符来工作。但是我的计算器存在缺陷,它无法处理负数分割,例如1 / -1。我是否了解RPn错误或我的中缀到postfix功能有问题?
检测数字和运算符
int isOperator(char e){
if(e == '+' || e == '-' || e == '*' || e == '/' || e == '^')
return 1;
else
return 0;
}
int isNumber(char c) {
if ((c>='0' && c<='9') || c=='.') {
return 1;
}
return 0;
}
将数学表达式转换为后缀
void pushPostfix(struct postfixStack* s,int item){
if(s->top == (100-1)){
printf("\nSTACK FULL");
}
else{
++s->top;
s->data[s->top]=item;
}
}
char popPostfix(struct postfixStack* s){
char a=(char)-1;
if(!isEmpty(s)){
a= s->data[s->top];
--s->top;
}
return a;
}
void infixToPostfix(char* infix, char * postfix) {
char *i, *p;
struct postfixStack stack;
char n1;
emptyStack(&stack);
i = &infix[0];
p = &postfix[0];
while (*i) {
while (*i == ' ' || *i == '\t') {
i++;
}
if (isNumber(*i)) {
while (isNumber(*i)) {
*p = *i;
p++;
i++;
}
*p = ' ';
p++;
}
if (*i == '(') {
pushPostfix(&stack, *i);
i++;
}
if (*i == ')') {
n1 = popPostfix(&stack);
while (n1 != '(') {
*p = n1;
p++;
*p = ' ';
p++;
n1 = popPostfix(&stack);
}
i++;
}
if (isOperator(*i)) {
if (isEmpty(&stack)) {
pushPostfix(&stack, *i);
}
else {
n1 = popPostfix(&stack);
while (priority(n1) >= priority(*i)) {
*p = n1;
p++;
*p = ' ';
p++;
n1 = popPostfix(&stack);
}
pushPostfix(&stack, n1);
pushPostfix(&stack, *i);
}
i++;
}
}
while (!isEmpty(&stack)) {
n1 = popPostfix(&stack);
*p = n1;
p++;
*p = ' ';
p++;
}
*p = '\0';
}
答案 0 :(得分:1)
您可以考虑这样的事情。
#define PLUS +
#define MINUS -
#define UMINUS _
#define DILIM_CLOSE 1
#define DILIM_OPEN 0
#define OPERAND 2
#define FACT !
// i is the present location being parsed in the infix string
// infix is an array holding the infix string
// this code can go to the tokeniser
// optr_type returns the type of operator, or even if it is an operand
if(infix[i]==PLUS || infix[i]==MINUS)
{
int sign=1,st=i;
while(infix[i]==PLUS || infix[i]==MINUS)
if(infix[i++]==MINUS)
sign*=-1;
if(sign==-1)
{
if((optr_type(infix[st-1])==OPERAND) ||optr_type(infix[st-1])==DILIM_CLOSE || infix[st-1]==FACT)
return MINUS;
else
return UMINUS;
}
if(sign==1)
{
if((optr_type(infix[st-1])==OPERAND) || optr_type(infix[st-1])==DILIM_CLOSE || infix[st-1]==FACT)
return PLUS;
else
return UPLUS;
}
}
当您检测到加号或减号后出现连续缺陷时,请继续翻转符号。如果是sign = -1
,那么您可以使用单个-
替换缺点条纹。例如--1 = 1
和---1 = -1
。在sigh == -1
条件下,如果保存在st
中的先前位置是操作数,关闭的paranthesis(任何类型)或阶乘符号,那么它是二进制减号,否则它必须是一元减号。与一元加一样。
一旦您将操作员标记为一元,就很容易评估,但您需要根据操作员的类型来决定。如果它是二进制的,则弹出两次并应用二元运算符,如果它是一元的,则弹出一次并应用运算符。