[問題] 四則運算問題
小弟在練習以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
12/30 00:11, 1F
→
12/30 00:12, , 2F
12/30 00:12, 2F
→
12/30 00:12, , 3F
12/30 00:12, 3F
→
12/30 00:12, , 4F
12/30 00:12, 4F
→
12/30 00:13, , 5F
12/30 00:13, 5F
→
12/30 08:52, , 6F
12/30 08:52, 6F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章