通过递归的方法实现简单表达式的运算,支持加减乘除以及多层括号运算。
//eval.h
//
//eval.h
#if !defined(__EVAL__H__)
#define __EVAL__H__
// evaluate the value of the str.
// It support +-*/ with non-nagetive integers only.
// @param str The string to be evaluated. This string is to be modified.
// @return the value evaluated.
int eval(char* str);
#endif
//eval.c
//
//eval.c
#include "eval.h"
#include <string.h>
#include <stdio.h>
#define CH2DEC(x) ((x) - '0')
// find the most right and lowest operator in the str
// @return -1 if no any operators in the str; or
// the index of the operator sepeicified in the str
static int findop(const char *str);
// return the rank of the operator
// @return -1 if the char ch is not an operator; or
// the rank listed as 1 for * and /, 2 for + and -
static int oprank(char ch);
// convert a string into a number.
// The string should consist of all digits.
// @return the converted number
static int str2int(const char *str);
// calculate a op b.
// It supports +-*/ as the op.
// @return the result of a op b
static int calc(int a, char op, int b);
int eval(char *str)
{
int ret = 0;
char str1[200];
int loc = findop(str);
if (loc == -1) ret = str2int(str);
else {
char op = str[loc];
str[loc] = '\0';
if (op == ')') {
int k;
for (k = 0; k < loc; k++) {
if (str[k] == '(') {
str[k] = '\0';
break;
}
}
int temp = eval(str + k + 1);
itoa(temp, str1, 5);
strcpy(str1, strcat(str, str1));
strcpy(str, strcat(str1, str + loc + 1));
ret = eval(str);
}
else {
int left = eval(str);
int right = eval(str + loc + 1);
ret = calc(left, op, right);
}
}
return ret;
}
static int findop(const char *str)
{
int i;
int ret = -1;
int lowestoprank = -1;
for (i = strlen(str) - 1; i >= 0; i--) {
int rank = oprank(str[i]);
if (rank == 0) {
ret = i;
break;
}
if (rank == 3 && oprank(str[i - 1]) > 0) rank = 1;
else if (rank > lowestoprank) {
ret = i;
lowestoprank = rank;
if (str[i - 1] == ')') break;
}
}
return ret;
}
static int oprank(char ch)
{
if (ch == '+' || ch == '-') return 3;
else if (ch == '*' || ch == '/') return 2;
else if (ch == ')') return 0;
else return -1;
}
static int str2int(const char *str)
{
int i;
int ret = 0;
for (i = 0; i < strlen(str); i++) ret = ret * 10 + CH2DEC(str[i]);
return ret;
}
static int calc(int a, char op, int b)
{
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
void meau()
{
printf(">> Welcome to the intelligent computing system!\n");
printf(">> Enter 1 for the operation and 0 for the exit!\n");
printf("\n>> Your choice:");
}
//main.c
//
//main.c
#include <stdio.h>
#include <assert.h>
#include <conio.h>
#include "eval.h"
int main()
{
char line[100];
int flag = 1;
while (flag)
{
meau();
int a;
scanf("%d", &a);
if (a == 1) {
printf("\n>> Please enter the string:");
scanf("%s", line);
printf(">> The result is:%s=", line);
printf("%d\n\n", eval(line));
}
else {
flag = 0;
break;
}
printf(">> Press any key to continue!");
getch();
system("cls");
}
printf("\n>> Welcome to use next time!");
}