计算器(Calculator)实验指南
- 前置知识
如果你不了解 C 语⾔中的 struct, enum, union, typedef 的⽤法,请你⾸先查阅课本或其他资料再来阅读本实
验指南。
如果你的⽬标为 100 分,建议不要急于开始,⾸先阅读实验指南的全⽂以进⾏合理的顶层设计,这可能⽐在原来的基础
上加东⻄更加节省时间。 - 总览
在读⼊了每⼀⾏语句之后,我们可能需要依次进⾏以下步骤。 - 词法分析
- 语法分析 & 表达式求值
- 变量赋值
⼤家会在《编译原理》课程中学会真正的词法分析和语法分析。这⾥,我们⼤致描述⼀下这些步骤分别都是在做什么


最终完成全部加分项, 得分97
部分代码如下:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define INT 73
#define FLOAT 70
#define VARIABLE 86
#define ERROR 1
typedef struct value {
int type;
union {
int iVal;
double fVal;
} val;
} Value;
typedef struct assignment {
char name[32];
Value val;
} Assignment;
Assignment assignment[300];
int assign_id = 0;
typedef struct token {
int type;
char str[32];
} Token;
Token tokens[200];
int token_id = 0;
int l, r;
void error();
Value eval(int l, int r);
int check_parentheses(int l, int r);
void print_token();
int check_minus(int l, int r);
int main_token(int l, int r);
Value meetValue(Value v1, Value v2, int op);
Value evalAssign(int l, int r);
void print_token(){
for(int i = 0; i < token_id; i++)
{
printf("token_id: %d type: %d %c str: %s\n", i, tokens[i].type, tokens[i].type, tokens[i].str);
}
}
void error(){
printf("Error\n");
}