[問題] 四則運算問題

看板C_and_CPP (C/C++)作者 (媽媽咪阿)時間13年前 (2012/12/29 23:15), 編輯推噓0(006)
留言6則, 2人參與, 最新討論串2/2 (看更多)
小弟在練習以C++物件導向方式寫四則運算的程式 可是在DEV-C++寫完在執行會出現"應用程式錯誤" 用除錯會跳出視窗說"引發了存取違規錯誤" 以下是小弟的程式碼~希望各位大大能夠幫我指點迷津 因為我實在找不到到底問題在哪裡... -------------------------------------------------------------- #include<cstdio> #include<cstdlib> #include<string.h> struct Listnode{ int num; char op; struct Listnode *prev,*next; }; class Operation{ private: struct Listnode head; public: Operation(char s[]){//將輸入串列轉成linked list char *sp=s; struct Listnode *ptr=&head; head.next=NULL; int num_temp=0,pow=1; while(*sp){ if(*sp=='+'||*sp=='-'||*sp=='*'||*sp=='/'){ struct Listnode *node=new struct Listnode; node->num=num_temp; node->op=*sp; node->next=NULL; node->next=ptr; ptr->next=node; ptr=node; } else{ num_temp=num_temp*pow+(*sp-48);//計算數字 pow=10; if(!*(sp+1)){ struct Listnode *node=new struct Listnode; node->num=num_temp; node->next=NULL; node->next=ptr; ptr->next=node; } } sp++; } }; void Merge(struct Listnode *a,struct Listnode *b){//節點合併 if(a->op=='+') b->num=a->num+b->num; else if(a->op=='-') b->num=a->num-b->num; else if(a->op=='*') b->num=a->num*b->num; else if(a->op=='/') b->num=a->num/b->num; b->prev=a->prev; a->prev->next=b; } void Operate(){//運算 struct Listnode *ptr=head.next; while(ptr->next){ if(ptr->op=='*'||ptr->op=='/'){ Merge(ptr,ptr->next); ptr=ptr->next; } } while(ptr->next){ if(ptr->op=='+'||ptr->op=='-') { Merge(ptr,ptr->next); ptr=ptr->next; } } } int Getnum(){ struct Listnode *ptr=head.next; return ptr->num; } }; int main() { char s[25]; printf("請輸入運算式:"); scanf("%s",s); Operation op=Operation(s); op.Operate(); printf("結果=%d",op.Getnum()); system("pause"); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.239.66.109

12/30 00:11, , 1F
node->prev 的值被 assign 到 node->next 了
12/30 00:11, 1F

12/30 00:12, , 2F
Merge 和解構子裡面沒把 new 出來的 node delete 掉
12/30 00:12, 2F

12/30 00:12, , 3F
num_temp 用完沒歸零
12/30 00:12, 3F

12/30 00:12, , 4F
Operate 裡面 ptr 沒前進
12/30 00:12, 4F

12/30 00:13, , 5F
Operate 裡面第二個 while 之前 ptr 沒重新初始化
12/30 00:13, 5F

12/30 08:52, , 6F
太感謝li大了~幫我發現問題所在~我真的太笨了...
12/30 08:52, 6F
文章代碼(AID): #1GtmaRLH (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1GtmaRLH (C_and_CPP)