b22bb5b7
1
/**********************************
2
题目:波兰式计算器
3
/* 以下是几个标准的表达式:
4
5 * 2 + -3
5
5 * (2 + -3)
6
5 + ((-4 * -5) + (((5 + (6 - 2)) * 7 + ((4 + 2) * (3 - 1))))
7
与之等价的波兰表达式为
8
+ * 5 2 -3
9
* 5 + 2 -3
10
+ 5 + * -4 -5 + * + 5 - 6 2 7 * + 4 2 - 3 1
11
12
Author:Linghucong
13
Date:2007-4-28
14
***********************************/
15
#include <math.h>
16
#include <stdio.h>
17
#include <string>
18
#include <iostream>
19
using namespace std;
20
21
void Polan(string test) {
22
string ops[100];
23
int opNum = -1;
24
int i = 0;
25
while (i < test.length())
26
{
27
//处理空格
28
if (test[i] == ' ') {
29
i++;
30
continue;
31
}
32
//处理操作符
33
if (test[i] == '+' || test[i] == '*' || (test[i] == '-' && test[i + 1] == ' ')) {
34
ops[++opNum] = test[i++];
35
continue;
36
}
37
//处理数字
38
for (int count =0; count < test.length() - i; count++) {
39
if (test[i + count] == ' ') {
40
break;
41
}
42
}
43
string str = test.substr(i, count);
44
i += count;
45
ops[++opNum] = str;
46
47
int res;
48
//算法:加入一个数字之后检查其前面一个值是不是数字,如果是,则计算,如果不是,继续往数组中添加值。
49
while (opNum > 1 && ops[opNum - 1] != "+" && ops[opNum - 1] != "*" && ops[opNum - 1] != "-") {
50
if (ops[opNum - 2] == "+") {
51
res = atoi(ops[opNum].c_str()) + atoi(ops[opNum - 1].c_str()) ;
52
opNum -= 2;
53
} else if(ops[opNum - 2] == "-") {
54
res = atoi(ops[opNum - 1].c_str()) - atoi(ops[opNum].c_str());
55
opNum -= 2;
56
} else if(ops[opNum - 2] == "*") {
57
res = atoi(ops[opNum].c_str()) * atoi(ops[opNum - 1].c_str());
58
opNum -= 2;
59
}
60
61
_itoa(res, (char *)ops[opNum].c_str(), 10);
62
if (opNum == 0) {
63
break;
64
}
65
}
66
}
67
68
cout << ops[0] << endl;
69
}
70

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

写的时候才发现原来这么一个小程序也是这么的不容易,费了好办天劲,总发现算法只能满足大部分的情况,后来索性放下程序,仔细研究算法规律,突然发现,其实比想象中的要简单许多。在网上找到的代码有好几百行,简直不是人看的呵呵。发现自己的编程能力真的有待提高:》