-
Notifications
You must be signed in to change notification settings - Fork 195
/
arithmetic.cxx
108 lines (104 loc) · 2.5 KB
/
arithmetic.cxx
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// ARITHMETIC EXPRESSION (cHAPTER 1.21)
// ---------------------------------
//
//This program takes an integer arithmetic expression in infix form
//and returns its prefix and postfix forms (with no parentheses)
//and its integer value.
// The complete documentation is in the book.
//
#include<stdio.h>
void copy(char* t, char* s, int n){
for(int i=0;i<n;i++)
t[i]=s[i];
t[n]='\n';
}
int fix(char* s, int length, int post){
for(int i=length-1;i>=0;i--)
if((s[i]=='+')||(s[i]=='-')){
char s1[i+1];
char s2[length-i];
copy(s1,s,i);
copy(s2,s+i+1,length-i-1);
if(post==2){
if(s[i]=='+')
return fix(s1,i,post) + fix(s2,length-i-1,post);
else
return fix(s1,i,post) - fix(s2,length-i-1,post);
}
if(post==0)printf("%c",s[i]);
fix(s1,i,post);
fix(s2,length-i-1,post);
if(post==1)printf("%c",s[i]);
return 0;
}
for(int i=length-1;i>=0;i--)
if(s[i]=='%'){
char s1[i+1];
char s2[length-i];
copy(s1,s,i);
copy(s2,s+i+1,length-i-1);
if(post==2)return fix(s1,i,post) % fix(s2,length-i-1,post);
if(post==0)printf("%c",s[i]);
fix(s1,i,post);
fix(s2,length-i-1,post);
if(post==1)printf("%c",s[i]);
return 0;
}
for(int i=length-1;i>=0;i--)
if((s[i]=='*')||(s[i]=='/')){
char s1[i+1];
char s2[length-i];
copy(s1,s,i);
copy(s2,s+i+1,length-i-1);
if(post==2){
if(s[i]=='*')
return fix(s1,i,post) * fix(s2,length-i-1,post);
else
return fix(s1,i,post) / fix(s2,length-i-1,post);
}
if(post==0)printf("%c",s[i]);
fix(s1,i,post);
fix(s2,length-i-1,post);
if(post==1)printf("%c",s[i]);
return 0;
}
if(*s == '\n'){
printf("error");
return 0;
}
if(post==2){
int sum=0;
int exp=1;
for(int i=length-1;i>=0;i--){
if((s[i]>='0')&&(s[i]<='9')){
sum += (s[i]-'0') * exp;
exp *= 10;
}
else{
printf("error");
return 0;
}
}
return sum;
}
for(int i=0;i<length;i++){
if((s[i]>='0')&&(s[i]<='9'))
printf("%c",s[i]);
else{
printf("error");
return 0;
}
}
return 0;
}
main(){
char* s = "3*5-5*3*1";
int i = 9;
//for(i=0; (s[i]=getchar()) != '\n'; i++);
fix(s,i,0); //prefix form
printf("\n");
fix(s,i,1); //postfix form
printf("\n");
printf("%d\n",fix(s,i,2)); //integer value
return 0;
}