关于c++包含两个幂符号时将中缀转换为后缀(^^)

About c++ convert infix to postfix when it contains two power signs (^^)

我的目标是将中缀表达式转换为后缀表达式。

这一行有问题:

while(precedence(stack[top])>=precedence(symbol)) 

当条件为 ++**/-- 时(并且应该)满足条件,因为它从左侧检查,但在 power 的情况下(^) 它从右边开始。如果是双倍功率(^^),我不想进入这个循环。

in simple in while(precedence(stack[top])>=precedence(symbol)) 如果top的operator是(^)and operator in symbol是(^)我不想进入while循环我将删除此案例,因为它是错误的,但我不知道如何。

C++:

#include<iostream>
#include<stdio.h>

using namespace std;#
define size 100

int temp, length = 0, inx = 0, pos = 0, top = -1;
char symbol, infix[size], postfix[size], stack[size];
void push(char);
char pop();
int precedence(char);
void infix_to_postfix(char[]);

void push(char symbol) {
    if (top >= size - 1) {
        cout << "stack is over flow push not possible" << endl;
    } else {
        top = top + 1;
        stack[top] = symbol;
    }
}

char pop() {
    temp = stack[top];
    top = top - 1;
    return temp;
}

int precedence(char symbol) {
    int priority = 0;
    switch (symbol) {
    case '+':
    case '-':
        priority = 1;
        break;

    case '*':
    case '/':
        priority = 2;
        break;
    case '^':
        priority = 3;
        break;
    } //end of switch()
    return priority;
} //end of precedence()

void infix_to_postfix(char infix[]) {
    while (infix[inx] != '[=11=]') {
        symbol = infix[inx++];
        switch (symbol) {
        case '(':
            push(symbol);
            break;
        case ')':
            temp = pop();
            while (temp != '(') {
                postfix[pos++] = temp;
                temp = pop();
            }
            break;
        case '-':
        case '+':
        case '*':
        case '/':
        case '^':
            while (precedence(stack[top]) >= precedence(symbol)) {
                temp = pop();
                postfix[pos++] = temp;
            }
            push(symbol);
            break;
        default:
            postfix[pos++] = symbol;
            break;
        }
    }

    while (top > -1) {
        temp = pop();
        postfix[pos++] = temp;
        postfix[pos] = '[=11=]';
    }
}

int main() {
    cout << "\nEnter an infix expression:\n";
    cin >> infix;
    infix_to_postfix(infix);
    cout << "\nThe equivalent postfix expression:\n";;
    cout << postfix << endl;;
    return 0;
}

in simple in while(precedence(stack[top])>=precedence(symbol)) if the operator in top is (^)and operator in symbol is (^)I do not want to enter while loop

使用

while (precedence(stack[top]) >= precedence(symbol) && stack[top] != '^' && symbol != '^')

向您的条件添加 && 将使其检查堆栈顶部的运算符和符号是否不是 '^'

你也可以

// ...

case '^':
    if (stack[top] != '^' && symbol != '^')
        while(precedence(stack[top])>=precedence(symbol))
        {
            temp=pop();
            postfix[pos++]=temp;
        }

    // ...