これは数回尋ねられたと思いますが、私が見た他の質問はあまり役に立ちませんでした. わかりましたので、ここに行きます: 中置式を後置式に変換する関数、プリプロセッサである関数、後置式を評価する関数の 3 つの関数があります。私が問題を抱えているのは、単項の負の式を評価することです。コード全体を入れると非常に長くなるので、マイナス/マイナスのケースを処理する部分のみを投稿します。
これが私の出力です: input: -3
after preprocess: 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];
}
私が犯したエラー(または私が行う必要のある編集)は、おそらく私には見えない本当に単純なものであるとほぼ確信しています(通常、私はそうです)が、正しい方向への微調整は高く評価されます!
**注: 関連すると思われる部分のみをコピーして貼り付けたため、コードの書式設定は正確ではない可能性があります。