C++ 사칙연산계산기인데 오류가머인지모르겠습니다
글쓴이: dongyop99 / 작성시간: 금, 2014/11/28 - 12:11오후
/* * main.cpp * * Created on: 2014. 11. 28. * Author: 1407 */ #include <iostream> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <fstream> using namespace std; #define max 128 #define null 0 long stack[max]; double sstack[max]; int top = -1; double ppush(double n) { top++; if(top > max){ cout <<" STACK OVERFLOW ! " << endl; exit(-1); } sstack[top] = n; return 1; } double ppop() { if(top < 0) return -1; return sstack[top--]; } long push(long n) { top++; if(top > max){ cout << "STACK OVERFLOW !" << endl; exit(-1); } stack[top] = n; return 1; } long pop() { if(top < 0) return -1; return stack[top--]; } int prior(int op) { switch(op){ case '(' : return 0; case '+' : case '-' : return 1; case '*' : case '/' : return 2; default : return 3; } } void postfix(char *postsik, char *sik) { while(*sik !=null){ if(*sik == '(') push(*sik++); else if(*sik == ')'){ while(stack[top] != '('){ *postsik++ = pop(); *postsik++ = ' '; } pop(); sik++; } else if(strchr("+-*/",*sik) !=null){ while(top >=0 && prior(stack[top]) >= prior(*sik)){ *postsik++ = pop(); *postsik++ = ' '; } push(*sik++); } else if(isdigit(*sik)){ do{ *postsik++ = *sik++; } while(isdigit(*sik) || *sik== '.'); *postsik++=' '; } else sik++; } while(top >= 0){ *postsik++ = pop(); *postsik++ = ' '; } postsik--; *postsik = null; } double calc(double a, int n) { int i; double x=a; //printf("---x=%f\n",x); for(i=0; i<n; i++) x=x/10; return x; } double post(char *p_sik) { double jungsu, sosu,suja; int cnt; double i, j; while(*p_sik){ if(isdigit(*p_sik)){ jungsu = 0; do{ jungsu = jungsu * 10+(*p_sik-'0'); p_sik++; } while(isdigit(*p_sik)); sosu=0; cnt=0; if(*p_sik=='.'){ p_sik++; do{ sosu=sosu*10+(*p_sik-'0'); p_sik++; cnt++; } while(isdigit(*p_sik)); sosu=calc(sosu,cnt); } suja=jungsu+sosu; ppush(suja); } else if(strchr("+-*/", *p_sik) !=null){ i = ppop(); j = ppop(); switch(*p_sik){ case '+' : ppush(j+i); break; case '-' : ppush(j-i); break; case '*' : ppush(j*i); break; case '/' : ppush(j/i); break; } p_sik++; } else p_sik++; } return pop(); } int main() { char postsik[max]; char sik[max]; cout << "산술식 입력 : "; gets(sik); postfix(postsik, sik); cout << "후위식 : " << postsik << endl; cout << "연산 결과 : " << post(postsik) << endl; }
산술식 입력 :(5.6+7.2)*(12.4-3.2)
후위식 : 5.6 7.2 + 12.4 3.2 - *
연산 결과 : 42
이렇게 결과가나오긴하는데 후위식 까지는 맞게 나오는데 연산결과가 왜 계속 멀입력해도 40~49사이에서 왓다갓다합니다
Forums:
return ppop();
.
댓글 달기