calculator

calculator

使用链表实现四则混合运算计算器(加减乘除和括号运算):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<stdio.h>
#include<stdlib.h>
struct Part{
double num;
char sign;
struct Part *Pnext;
};

struct Part *create();
struct Part *transfer(struct Part *phead);
double caculate(struct Part *phead);

int main()
{
struct Part *phead;
phead=create();
phead=transfer(phead);
printf("\n%lf",caculate(phead));
return 0;
}

struct Part *create()
{
struct Part *phead=0,*ptemp=0,*ptail=0;
double num;char sign;
printf("****Welcome to magic caculator!****\n");
printf("Input:");
scanf("%lf%c",&num,&sign);
while (1){
ptemp=(struct Part *)malloc(sizeof(struct Part));
ptemp->num=num;
ptemp->sign=sign;
ptemp->Pnext=0;
if (!phead)
phead=ptail=ptemp;
else {
ptail->Pnext=ptemp;
ptail=ptemp;
}
if (sign=='='||sign=='\n')
break;
scanf("%lf%c",&num,&sign);
}
return phead;
}

struct Part *transfer(struct Part *phead)
{
struct Part *phead1;struct Part *p;
phead1=phead;
if (phead->sign=='*'){
(phead->Pnext)->num=phead->num*(phead->Pnext)->num;
phead->num=0;
phead->sign='+';}
if (phead->sign=='/'){
(phead->Pnext)->num=phead->num/(phead->Pnext)->num;
phead->num=0;
phead->sign='+';}
p=phead;
phead=phead->Pnext;
while (phead->sign!='='&&phead->sign!='\n'){
if (phead->sign=='*'){
(phead->Pnext)->num=phead->num*(phead->Pnext)->num;
phead->num=0;
if (p->sign=='+')
phead->sign='+';
else phead->sign='-';
}

if (phead->sign=='/'){
(phead->Pnext)->num=phead->num/(phead->Pnext)->num;
phead->num=0;
if (p->sign=='+')
phead->sign='+';
else phead->sign='-';
}
p=phead;
phead=phead->Pnext;
}
return phead1;
}

double caculate(struct Part *phead)
{
double sum=phead->num;
while (phead->sign!='\n'&&phead->sign!='='){
if(phead->sign=='-')
sum=sum-(phead->Pnext)->num;
if(phead->sign=='+')
sum=sum+(phead->Pnext)->num;
phead=phead->Pnext;
}
return sum;
}