目前,我正在制作一个计算器,输入数学表达式,并使用RPn进行计算。因此,我使用中缀到后缀的转换函数来转换它。计算器通过将数字压入堆栈和检测运算符来工作。但是我的计算器有一个缺陷,它不能处理像1/-1这样的负数除法。我是不是理解错了RPn或者我的后缀函数有问题?
检测数字和运算符
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';
}发布于 2018-05-25 04:50:01
你可以考虑这样的事情。
#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。在sign == -1条件中,如果保存在st中的前一个位置是操作数、右括号(任何类型)或阶乘符号,则它是一个二进制减号,否则它一定是一个一元减号。一元加号也是如此。
一旦你将运算符标记为一元,它就很容易计算,但你需要根据运算符的类型来决定。如果是二进制,则弹出两次并应用二元运算符;如果是一元,则弹出一次并应用运算符。
https://stackoverflow.com/questions/50517413
复制相似问题