我敢肯定这已经被问过几次了,但我看到的其他问题并没有真正帮助我。好吧,就这样吧:我有三个函数,一个将中缀表达式转换为后缀,一个是预处理器,一个是评估后缀表达式。我遇到的问题是评估一元否定表达式。如果我输入我的整个代码,它会很长,所以我只会发布处理负/负情况的部分:
这是我的输出:输入:
预处理后的-3:3 postfix = -3 然后是分段错误,它应该输出“total = -3”
#include "postfix.h"
#include "stack.h"
#include <cstdlib>
#include <cmath>
#include <cstdio>
void eval_postfix(char* postfix){
Stack<double> stack;
char fchar[100];
int j=0;
double a, b, convert, total = 0.0;
for(int i=0; postfix[i] != '\0'; i++){
switch(postfix[i]){
case '-':
a = stack.top();
stack.pop();
b = stack.top();
stack.pop();
total = b-a;
stack.push(total);
break;
我很确定错误出在函数的那部分,我一直在尝试不同的东西,但没有任何效果,我得到分段错误或零的次数更多。我最初尝试应用我在 infix2postfix 表达式中所做的事情(这显然不起作用)但这是我的其余代码用于否定/减去案例......
void infix2postfix(char* infix, char* postfix){
Stack<char> stack;
stack.push('\0');
int pc = 0;
bool c;
for(unsigned int i = 0; infix[i] != '\0'; i++){
//use the switch method to define what to do for each of the operators
switch(infix[i]){
case '-':
c = 0;
//unary negative
if(i==0){
postfix[pc++] = infix[i];
c = 1;
}
else if((infix[i-1] == '*' ||
infix[i-1] == '^' ||
infix[i-1] == '*' ||
infix[i-1] == '/' ||
infix[i-1] == '+' ||
infix[i-1] == '-')&&
i>0){
postfix[pc++]= infix[i];
c=1;
}
else{
if(stack.top() == '*' || stack.top() == '/' || stack.top() == '^'){
while(stack.top() != '\0' && stack.top() != '('){
postfix[pc++] = stack.top();
postfix[pc++] = ' ';
stack.pop();
}
}
}
if (c==0)
stack.push('-');
break;
void preprocessor(char* input){
char output[100];
int oc = 0;
for(unsigned int i=0; input[i] != '\0'; i++){
if((input[i] == '-' && (input[i-1] == '*' || input[i-1] == '^' || input[i-1] == '*'
|| input[i-1] == '/' || input[i-1] == '+' || input[i-1] == '-')
&& i>0)){
//output[oc++] = '0';
output[oc++] = input[i];
}
我几乎可以肯定,无论我犯了什么错误(或我需要做的任何编辑)都可能是我看不到的非常简单的事情(因为我通常就是这种情况),但任何朝着正确方向轻推都会不胜感激!
**注意:我的代码格式可能不准确,因为我只复制并粘贴了我认为相关的部分。