Просмотр исходного кода

eval simple numeric expressions.

Lucas Stadler лет назад: 11
Родитель
Сommit
f74e5ce976
1 измененных файлов с 29 добавлено и 1 удалено
  1. 29 1
      c/mul/main.c

+ 29 - 1
c/mul/main.c

4
4
5
#include "mpc.h"
5
#include "mpc.h"
6
6
7
long eval_op(long x, char* op, long y) {
8
	if (strcmp(op, "+") == 0) { return x + y; }
9
	if (strcmp(op, "-") == 0) { return x - y; }
10
	if (strcmp(op, "*") == 0) { return x * y; }
11
	if (strcmp(op, "/") == 0) { return x / y; }
12
	return 0;
13
}
14
15
long eval(mpc_ast_t* t) {
16
	if (strstr(t->tag, "number")) {
17
		return atoi(t->contents);
18
	}
19
20
	char* op = t->children[1]->contents;
21
	long x = eval(t->children[2]);
22
23
	int i = 3;
24
	while (strstr(t->children[i]->tag, "expr")) {
25
		x = eval_op(x, op, eval(t->children[i]));
26
		i++;
27
	}
28
29
	return x;
30
}
31
7
int main(int argc, char** argv) {
32
int main(int argc, char** argv) {
8
	mpc_parser_t* Number = mpc_new("number");
33
	mpc_parser_t* Number = mpc_new("number");
9
	mpc_parser_t* Operator = mpc_new("operator");
34
	mpc_parser_t* Operator = mpc_new("operator");
27
52
28
		mpc_result_t r;
53
		mpc_result_t r;
29
		if (mpc_parse("<stdin>", input, Lang, &r)) {
54
		if (mpc_parse("<stdin>", input, Lang, &r)) {
30
			mpc_ast_print(r.output);
55
			mpc_ast_t* t = r.output;
56
			mpc_ast_print(t->children[1]);
57
			long result = eval(t->children[1]);
58
			printf("%li\n", result);
31
			mpc_ast_delete(r.output);
59
			mpc_ast_delete(r.output);
32
		} else {
60
		} else {
33
			mpc_err_print(r.error);
61
			mpc_err_print(r.error);