题目1101:计算表达式
- 题目描述:
-
对于一个不存在括号的表达式进行计算
- 输入:
-
存在多种数据,每组数据一行,表达式不存在空格
- 输出:
-
输出结果
- 样例输入:
-
6/2+3+3*4
- 样例输出:
-
18
这道题本身不难,求解有多种方法,但我却做了很多次wrong answer,一开始的代码是这样1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 6 7 int main(int argc, char const *argv[]) 8 { 9 bool isStart = true; 10 int temp; 11 int state = 0; 12 int ans; 13 char opt; 14 int toDeal; 15 16 //freopen("input.txt","r",stdin); 17 while(scanf("%d%c",&toDeal,&opt) != EOF) { 18 if(isStart) { 19 temp = 1; 20 ans = 0; 21 state = 0; 22 isStart = false; 23 } 24 25 if(state == 0) { 26 temp = temp * toDeal; 27 } 28 else { 29 temp = temp/toDeal; 30 } 31 32 if(opt == '+') { 33 ans = ans + temp; 34 temp = 1; 35 state = 0; 36 } 37 else if(opt == '-') { 38 ans = ans + temp; 39 temp = -1; 40 state = 0; 41 } 42 else if(opt == '*') { 43 state = 0; 44 } 45 else if(opt == '/') { 46 state = 1; 47 } 48 else { 49 ans = ans + temp; 50 printf("%d\n", ans); 51 isStart = true; 52 } 53 54 } 55 return 0; 56 }
最后发现原因是最后一行的数据opt是读不出来的,else在本地能进去,但在oj系统上就不知道了,开始修改成如下代码:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 6 7 int main(int argc, char const *argv[]) 8 { 9 int temp; 10 int state = 0; 11 int ans; 12 char opt; 13 int toDeal; 14 15 //freopen("input.txt","r",stdin); 16 while(scanf("%d",&toDeal) != EOF) { 17 temp = 1; 18 ans = 0; 19 state = 0; 20 while(scanf("%c",&opt)!=EOF&&(opt=='+'||opt=='-'||opt=='*'||opt=='/')) { 21 if(state == 0) { 22 temp = temp * toDeal; 23 } 24 else { 25 temp = temp/toDeal; 26 } 27 if(opt == '+') { 28 ans = ans + temp; 29 temp = 1; 30 state = 0; 31 } 32 else if(opt == '-') { 33 ans = ans + temp; 34 temp = -1; 35 state = 0; 36 } 37 else if(opt == '*') { 38 state = 0; 39 } 40 else if(opt == '/') { 41 state = 1; 42 } 43 scanf("%d",&toDeal); 44 } 45 if(state == 0) { 46 temp = temp * toDeal; 47 } 48 else { 49 temp = temp/toDeal; 50 } 51 ans = ans + temp; 52 printf("%d\n", ans); 53 } 54 return 0; 55 }
之后又做了修改
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 6 7 int main(int argc, char const *argv[]) 8 { 9 int temp = 1; 10 int state = 0; 11 int ans = 0; 12 char opt; 13 int toDeal; 14 15 //freopen("input.txt","r",stdin); 16 while(scanf("%d",&toDeal) != EOF) { 17 if(state == 0) { 18 temp = temp * toDeal; 19 } 20 else { 21 temp = temp/toDeal; 22 } 23 24 if(scanf("%c",&opt) != EOF) { 25 if(opt == '+' || opt == '-') { 26 ans = ans + temp; 27 temp = 1 - (opt - '+'); 28 state = 0; 29 } 30 else if(opt == '*') { 31 state = 0; 32 } 33 else if(opt == '/') { 34 state = 1; 35 } 36 else if(opt == '\n') { 37 ans = ans + temp; 38 printf("%d\n", ans); 39 temp = 1; 40 ans = 0; 41 state = 0; 42 } 43 } 44 else { 45 ans = ans + temp; 46 printf("%d\n", ans); 47 temp = 1; 48 ans = 0; 49 state = 0; 50 } 51 } 52 return 0; 53 }
主要的思路是把每一个乘除法作为一个temp,最后的结果是temp的累加和。