运行calc,进入下面的操作:

>>9
9
>>3+3
6
>>3*6
18
>>3*5/2
7.5
>>2/3
0.666667
>>quit

>>是提示符。

限制:

计算器源代码包含在词法分析器和语法分析器的压缩包里,HTML格式的源码 calc.cpp.html。因为Parser不接受表达式,所以我人为地给输入缓存加上a=,从而与输入的表达式成为一个赋值语句。

 1  /**************************************************
 2  * file: calc.cpp
 3  * date: 2006-06-30
 4  * author: ideawu
 5  * describe: a really small and simple caculator.
 6  *           with known bugs.
 7  **************************************************/
 8
 9  #include <stdio.h>
10  #include <stdlib.h>
11  #include <string.h>
12
13  #include "Parser.h"
14
15  float calc(SyntaxTree *tree);
16
17  int main(int argc, char* argv[]){
18      char buf[1024] = "a=";
19      SyntaxTree *tree = NULL;
20      Lexer *lexer = new Lexer();
21      Parser *parser = new Parser();
22
23      lexer->setSrc(buf, 1024);
24      parser->setLexer(lexer);
25
26      printf(">>");
27      scanf("%s", &buf[2]);
28      while(strcmp(buf, "a=quit") != 0){
29          tree = parser->parse();
30
31          if(tree!=NULL){
32              //tree->display();
33              printf("%g\n", calc(tree->getRight()));
34          }else{
35              parser->printError();
36          }
37          printf(">>");
38          scanf("%s", &buf[2]);
39          parser->reset();
40      }
41
42      printf("\n");
43
44      return 0;
45  }
46
47  float calc(SyntaxTree *tree){
48      float a=0, b=0, val=0;
49
50      if(tree != NULL){
51          if(tree->getRootNode()->getType() == NUM){
52              return tree->getRootNode()->getValue();
53          }
54          a = calc(tree->getLeft());
55          b = calc(tree->getRight());
56
57          switch(tree->getRootNode()->getType()){
58              case PLUS:
59                  val = a + b;
60                  break;
61              case MINUS:
62                  val = a - b;
63                  break;
64              case MUL:
65                  val = a * b;
66                  break;
67              case DIV:
68                  if(b != 0){
69                      val = a / b;
70                  }
71                  break;
72              default:
73                  break;
74          }
75      }
76
77      return val;
78
79  }
80
81