# P1022 improvement of calculator (Analog & string)

2021-08-10 08:04:02

## P1022 The improvement of calculator （ simulation & character string ）

Subject portal

The question ： Enter a unary linear equation string , solve .

Ideas ： It's a bit like a suffix expression , However, it is necessary to judge whether it is a number or a letter . Whenever a letter is read, the coefficients before the letter are summed , If you encounter an operator, sum the numbers before the operator . With “=” For boundaries , Move all to one side , Finally, divide the coefficients to get the result , Be careful -X=0 The situation of .

``````#include<bits/stdc++.h>
using namespace std;
int num,x,b,f[3]={1,1,0};//f[0] Indicates that the number is on the side of the equal sign ：1 For the left ,-1 For the right .
int main(){ //f[1] Indicates whether the sign in front of the number is positive or negative ,1 Being positive ,-1 Negative .
char c,ch;//f[2] Indicates whether the character is a number
while((c=getchar())!='\n'){
if(isdigit(c)){
num=num*10+c-'0';
f[2]=1;
}
if(isalpha(c)){// When a letter is encountered, the coefficient before the letter is calculated .
if(f[2]) x+=f[0]*f[1]*num,num=0;
else x+=f[0]*f[1];
ch=c,f[2]=0;
}
if(c=='+') 	b+=f[0]*f[1]*num,num=f[2]=0,f[1]=1;// When an operator is encountered , Operate on the previous number .
if(c=='-')  b+=f[0]*f[1]*num,num=f[2]=0,f[1]=-1;
if(c=='=')  b+=f[0]*f[1]*num,num=f[2]=0,f[0]=-1,f[1]=1;
}
b+=f[0]*f[1]*num;// If the last one is a number, add .
double ans=(-b*1.0/x);
if(ans==0) printf("%c=0.000\n",ch);
else printf("%c=%.3lf\n",ch,ans);
return 0;
}
```

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.
```

https://chowdera.com/2021/08/20210810080205529x.html