标签:
括号匹配与括号随机生成不好解决,故使用了读文本文件取算式的方法。
去年数据结构课上实现了中缀转后缀并求值的小程序,在基础上进行了修改。
对于答案正确与否的匹配,用cal函数将原题计算一次,再将答案计算一次,两者误差小于一固定值(十万分之一),即为正确。
以下为代码:
1 #include <cstdlib>
2 #include <iostream>
3 #include <stdlib.h>
4 #include <iomanip>
5 #include <string>
6 using namespace std;
7 #define MAXSIZE 99
8 #define ERROR 0.00001
9 class node
10 {
11 public:
12 char oper;
13 double value;
14 node *next;
15 node(char c, double v, node *nextval)
16 {
17 oper = c;
18 value = v;
19 next = nextval;
20 }
21 ~node() {};
22 };
23 class stack
24 {
25 public:
26 node *top;
27 stack()
28 {
29 node *head = new node(‘ ‘, 0, NULL);
30 top = head;
31 }
32 /*~stack()
33 {
34 node *tem;
35 while (top->next != NULL)
36 {
37 tem = top;
38 top = top->next;
39 delete tem;
40 }
41 }*/
42 void push(char c, double v)
43 {
44 node *tem = new node(c, v, top);
45 top = tem;
46 }
47 node* pop()
48 {
49 node *tem;
50 tem = top;
51 top = top->next;
52 return tem;
53 }
54 };
55
56 double cal(char* s);
57
58 int main()
59 {
60 int wrong = 0;
61 int right = 0;
62 int i = 0;
63 double a1, a2;
64 FILE *fp;
65 char s[50];
66 if ((fp = fopen("test.txt", "r")) == NULL)
67 {
68 cout << "ERROR" << endl;
69 }
70 else
71 {
72 for (i = 0; i < 10; i++)
73 {
74 fgets(s, MAXSIZE, fp);
75 cout << s;
76 strcat(s, "");
77 a1 = cal(s);
78 cout << "result:";
79 cin >> s;
80 strcat(s, "");
81 a2 = cal(s);
82 if (abs(a1 - a2) <= ERROR)
83 {
84 right++;
85 cout << "RIGHT!" << endl;
86 }
87 else
88 {
89 wrong++;
90 cout << "WRONG!" << endl;
91 }
92 }
93 }
94 cout <<"正确:"<<right <<" "<<"错误:" <<wrong << endl;