当前位置:首页 » 编程语言 » c语言能实现eval函数吗
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

c语言能实现eval函数吗

发布时间: 2022-12-21 06:55:07

c语言表达式求值

//表达式求值
//By:jimly
//10/10/2009
//例如:输入2+2(4-6*3)=
//以"="结束,然后回车即出结果
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <assert.h>
typedef float ElemType;
typedef struct Stack
{
ElemType *base; // 栈基址
ElemType *top; // 栈顶
int stacksize; // 栈存储空间的尺寸
} SqStack;
/*------------------------------------------------------------
// 栈的基本操作
------------------------------------------------------------*/
bool InitStack(SqStack *S);
bool InitStack(SqStack *S);
void DestroyStack(SqStack *S);
bool StackEmpty(SqStack S);
int StackLength(SqStack S);
ElemType GetTop(SqStack S, ElemType *e);
void StackTraverse(SqStack S, void (*fp)(ElemType));
bool Push(SqStack *S, ElemType e);
bool Pop(SqStack *S, ElemType *e);
/*------------------------------------------------------------
// 表达式求值的操作函数定义
------------------------------------------------------------*/
char Precede(char A1,char A2);
ElemType Operate(ElemType a,ElemType theta,ElemType b);
bool In(char c,char op[]);
ElemType EvaluateExpression();
void Menu();//////////////////////////////////////////////
// Eval_exdivssion.cpp 表达式求值实现函数 //
//////////////////////////////////////////////
/*------------------------------------------------------------
操作目的: 判定运算符栈的栈顶运算符A1和读入的运算符A2之间优先关系的函数
初始条件: 无
操作结果: 判断出优先关系
函数参数:
char A1 运算符
char A2 运算符
返回值:
char 大小关系
------------------------------------------------------------*/
char Precede(char A1,char A2)
{
if (A1 == '+' || A1 == '-')
{
if (A2 == '+' || A2 == '-' || A2 == ')' || A2 == '=')
{
return '>';
}
else
return '<';
}
if (A1 == '*' || A1 == '/')
{
if (A2 == '(')
{
return '<';
}
else
return '>';
}
if (A1 == '(')
{
if (A2 == ')')
{
return '=';
}
if (A2 == '=')
{
return 'E';
}
else
return '<';
}
if (A1 == ')')
{
if (A2 == '(')
{
return 'E';
}
if (A2 == '=')
{
return 'E';
}
else
return '>';
}
if (A1 == '=')
{
if (A2 == '=')
{
return '=';
}
else
return '<';
}
else
return '=';
}
/*------------------------------------------------------------
操作目的: 二元运算a与b的函数
初始条件: 无
操作结果: 返回运算结果
函数参数:
ElemType a 操作数
ElemType theta 操作符
ElemType b 操作数
返回值:
ElemType 运算结果
------------------------------------------------------------*/
ElemType Operate(ElemType a,ElemType theta,ElemType b)
{
switch(char(theta))
{
case '+':
return a += b;
break;
case '-':
return a -= b;
break;
case '*':
return a *= b;
break;
case '/':
if(b==0)
{
printf("除数不能为0!!\n");
exit(0);
}
return a /= b;
break;
} return 0;
}
/*------------------------------------------------------------
操作目的: 判断字符c是否属于运算符集合op
初始条件: 无
操作结果: 返回判断结果
函数参数:
char c 要判断的字符
char op[] 运算符集合
返回值:
bool 属于返回true 否则返回false
------------------------------------------------------------*/
bool In(char c,char op[])
{
for (int i = 0;i<7;i++)
{
if (op[i] == c)
return true;
}
return false;
}
/*------------------------------------------------------------
操作目的: 算术表达式求值的运算符优先算法
初始条件: 无
操作结果: 返回表达式的值
函数参数:

返回值:
ElemType 运算结果
------------------------------------------------------------*/
ElemType EvaluateExpression()
{
SqStack OPTR; //运算符栈
SqStack OPND; //运算数栈
char Ct = '='; //判断是否结束的标识
int i = 0,j = 1;
ElemType e = 0,t = 0,c;
char op[7] = {'+','-','*','/','(',')','='}; InitStack(&OPTR); //初始化
Push(&OPTR,Ct);
InitStack(&OPND); //初始化 c = (float)getchar();
while (c!='=' || GetTop(OPTR,&e)!='=')
{
if (!In((char)c,op)) //不是运算e符进栈
{
while(!In((char)c,op)) //可以是几位数
{
t = t*10+(c-48);
c = (float)getchar();
}
Push(&OPND,t);
t = 0;
} else
{
switch (Precede((char)GetTop(OPTR,&e),(char)c))
{
case '<'://栈顶元素优先权低
Push(&OPTR,c);
c = (float)getchar();
break;
case '='://脱括号并接受下个字符
ElemType x;
Pop(&OPTR,&x);
c = (float)getchar();
break;
case '>'://退栈并将运算结果入栈
ElemType b,theta,a;
Pop(&OPTR,&theta);
Pop(&OPND,&b);
Pop(&OPND,&a);
Push(&OPND,Operate(a,theta,b));
break;
case 'E':
printf("括号不匹配!!\n");
exit(0);
break;

}
}
}
ElemType tem = GetTop(OPND,&e);
DestroyStack(&OPND);
DestroyStack(&OPTR);
return tem;
}/***
*DynaSeqStack.cpp - 动态顺序栈,即栈的动态顺序存储实现
****/
const int STACK_INIT_SIZE = 100; // 初始分配的长度
const int STACKINCREMENT = 10; // 分配内存的增量
/*------------------------------------------------------------
操作目的: 初始化栈
初始条件: 无
操作结果: 构造一个空的栈
函数参数:
SqStack *S 待初始化的栈
返回值:
bool 操作是否成功
------------------------------------------------------------*/
bool InitStack(SqStack *S)
{
assert(S != NULL);
S->base = (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);

if(S->base == NULL) return false; S->top = S->base;
S->stacksize = STACK_INIT_SIZE; return true;
}/*------------------------------------------------------------
操作目的: 销毁栈
初始条件: 栈S已存在
操作结果: 销毁栈S
函数参数:
SqStack *S 待销毁的栈
返回值:

------------------------------------------------------------*/
void DestroyStack(SqStack *S)
{
assert(S != NULL); free(S->base);
S->top = S->base = NULL;
}/*------------------------------------------------------------
操作目的: 判断栈是否为空
初始条件: 栈S已存在
操作结果: 若S为空栈,则返回true,否则返回false
函数参数:
SqStack S 待判断的栈
返回值:
bool 是否为空
------------------------------------------------------------*/
bool StackEmpty(SqStack S)
{
assert((S.base != NULL) && (S.top != NULL));
return(S.base == S.top);
}/*------------------------------------------------------------
操作目的: 得到栈的长度
初始条件: 栈S已存在
操作结果: 返回S中数据元素的个数
函数参数:
SqStack S 栈S
返回值:
int 数据元素的个数
------------------------------------------------------------*/
int StackLength(SqStack S)
{
assert((S.base != NULL) && (S.top != NULL));
return(S.top-S.base);
}/*------------------------------------------------------------
操作目的: 得到栈顶元素
初始条件: 栈S已存在
操作结果: 用e返回栈顶元素
函数参数:
SqStack S 栈S
ElemType *e 栈顶元素的值
返回值:
bool 操作是否成功
------------------------------------------------------------*/
ElemType GetTop(SqStack S, ElemType *e)
{
assert((S.base != NULL) && (S.top != NULL));
if(StackEmpty(S)) return false; *e = *(S.top-1);
return *e;
}/*------------------------------------------------------------
操作目的: 遍历栈
初始条件: 栈S已存在
操作结果: 依次对S的每个元素调用函数fp
函数参数:
SqStack S 栈S
void (*fp)() 访问每个数据元素的函数指针
返回值:

------------------------------------------------------------*/
void StackTraverse(SqStack S, void (*fp)(ElemType))
{
assert((S.base != NULL) && (S.top != NULL));
for(; S.base<S.top; S.base++) (*fp)(*S.base);
}/*------------------------------------------------------------
操作目的: 压栈——插入元素e为新的栈顶元素
初始条件: 栈S已存在
操作结果: 插入数据元素e作为新的栈顶
函数参数:
SqStack *S 栈S
ElemType e 待插入的数据元素
返回值:
bool 操作是否成功
------------------------------------------------------------*/
bool Push(SqStack *S, ElemType e)
{
if (S->top - S->base>=S->stacksize)
{
S->base = (ElemType *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!S->base)
exit(0);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e; return true;
}/*------------------------------------------------------------
操作目的: 弹栈——删除栈顶元素
初始条件: 栈S已存在且非空
操作结果: 删除S的栈顶元素,并用e返回其值
函数参数:
SqStack *S 栈S
ElemType *e 被删除的数据元素值
返回值:
bool 操作是否成功
------------------------------------------------------------*/
bool Pop(SqStack *S, ElemType *e)
{
if(S == NULL) return false;
assert((S->base != NULL) && (S->top != NULL));
if(StackEmpty(*S)) return false; *e = *(--S->top);
return true;
}//////菜单///////
void Menu()
{
printf("表达式求值模拟程序\n\n");

printf("功能菜单:\n");
printf("==============\n");
printf("[1] 输入表达式并求值\n");
printf("[0] 退出 \n");
printf("==============\n");
printf("请输入你的选择(0~1)(以回车结束):");
}///////// 主函数 ///////////
//////////////////////////////
int main()
{
char ch = ' ',tp; do
{
system("cls");
Menu();
ch = getchar();
if (ch == '0')
break;
tp = getchar();
printf("请输入一个表达式(最后输入”=“,然后回车出结果):");
printf("这个表达式结果为:%g\n",EvaluateExpression());
tp = getchar();
printf("任意键继续...");
getch();
} while (true); return 0;
}//end

② 如何用C语言实现MATLAB中eval函数的功能

eval_r()函数的功能就是将括号内的字符串视为语句并运行
例如: eval_r('y1=sin(2)')就是相当于在matlab命令窗口输入了y1=sin(2)这条命令。

③ C语言怎么动态创建函数

C语言可以通过宏,在你需要的位置宏展开出一个新的函数。
例如:
#define XXX(funcname) \
int funcname (int arg1, int arg2) \
{ return arg1 + arg2; }
但这也是编译期就决定好了的,也不能实现运行期动态创建。

④ 数据结构c语言版表达式求值标准程序

思路:中缀表达式-后缀表达式-求值

参考代码:

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <algorithm>

// 堆栈的数组实现,数组的大小固定。
template<class T>
class stack
{
private:
T *s; // 数组的首地址(栈底)
size_t N; // 指向栈顶第一个空闲块
const size_t size; // 堆栈的大小,固定不变

public:
stack(size_t n) : size(n)
{
s = new T[n]; // 可能抛出异常
N = 0; // 设置栈顶指针
}

~stack()
{
delete [] s;
}

bool empty() const
{
return N == 0;
}

bool full() const
{
return N == size;
}

void push(const T &object)
{
if (full())
{
throw "error: stack is full !";
}

s[N++] = object;
}

T pop()
{
if (empty())
{
throw "error: stack is empty !";
}

return s[--N];
}

T peek() const
{
if (empty())
{
throw "error: stack is empty !";
}

return s[N-1];
}

friend std::ostream& operator<<(std::ostream& os, const stack<T> &stk)
{
for (size_t i = 0; i < stk.N; i++)
{
std::cout << stk.s[i] << " ";
}

return os;
}
};

// 堆栈的链表实现
template<class T>
class STACK
{
private:
typedef struct node
{
T item;
node *next;
node(T x, node *t = NULL) : item(x), next(t) {}
}*link;

link head; // 指向栈顶第一个有效对象

public:
STACK(size_t n)
{
head = NULL;
}

~STACK() // 也可以用pop的方法删除,但效率低
{
link t = head;

while (t != NULL)
{
link d = t;
t = t->next;
delete d;
}
}

bool empty() const
{
return head == NULL;
}

bool full() const
{
return false;
}

void push(const T &object)
{
head = new node(object, head);
}

T pop()
{
if (empty())
{
throw "error: stack is empty !";
}

T v = head->item;
link t = head->next;
delete head;
head = t;
return v;
}

T peek() const
{
if (empty())
{
throw "error: stack is empty !";
}

return head->item;
}

friend std::ostream& operator<<(std::ostream& os, const STACK<T> &stk)
{
for (link t = stk.head; t != NULL; t = t->next)
{
std::cout << t->item << " ";
}

return os;
}
};

// 中缀表达式转化为后缀表达式,仅支持加减乘除运算、操作数为1位十进制非负整数的表达式。
char* infix2postfix(const char *infix, char *postfix)
{
const size_t N = strlen(infix);

if (N == 0 || postfix == NULL)
{
return postfix;
}

stack<char> opcode(N); // 堆栈存放的是操作符

for (size_t i = 0; i < N; i++)
{
switch (infix[i])
{
case '(': // 直接忽略左括号
break;

case ')': // 弹出操作符
*postfix++ = opcode.pop();
*postfix++ = ' ';
break;

case '+':
case '-':
case '*':
case '/':
opcode.push(infix[i]); // 压入操作符
break;

default:
if (isdigit(infix[i])) // 如果是数字,直接输出
{
*postfix++ = infix[i];
*postfix++ = ' ';
}
}
}

return postfix;
}

// 后缀表达式转化为中缀表达式,仅支持加减乘除运算、操作数为1位十进制非负整数的表达式。
char* postfix2infix(const char *postfix, char *infix)
{
const size_t N = strlen(postfix);

if (N == 0 || infix == NULL)
{
return infix;
}

*infix = '\0'; // 初始化输出字符串为空串
std::vector<std::string> v;

// 初始化,将所有有效字符放入容器
for (size_t i = 0; i < N; i++)
{
if (isdigit(postfix[i]) || postfix[i] == '+'
|| postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/')
{
v.push_back(std::string(1, postfix[i]));
}
}

// 处理每一个操作符
for (std::vector<std::string>::iterator b = v.begin(); b < v.end(); b++)
{
if (*b == "+" || *b == "-" || *b == "*" || *b == "/")
{
(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
std::cout << "------------------------------------------------" << std::endl;

std::string opcode = *(b);
std::string oprand1 = *(b - 2);
std::string oprand2 = *(b - 1);
b = v.erase(b - 2, b + 1); // 删除原来的三个表达式,用一个新的表达式替换
b = v.insert(b, std::string("(") + oprand1 + opcode + oprand2 + std::string(")"));
}
}

for (std::vector<std::string>::iterator b = v.begin(); b < v.end(); b++)
{
strcat(infix, (*b).c_str());
}

return infix;
}

// 计算后缀表达式的值,仅支持加减乘除运算、操作数为非负整数的表达式。
int postfix_eval(const char * postfix)
{
const size_t N = strlen(postfix);

if (N == 0)
{
return 0;
}

STACK<int> operand(N); // 堆栈存放的是操作数

for (size_t i = 0 ; i < N; i++)
{
switch (postfix[i])
{
int op1, op2;

case '+':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 + op2);
break;

case '-':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 - op2);
break;

case '*':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 * op2);
break;

case '/':
op1 = operand.pop();
op2 = operand.pop();
operand.push(op1 / op2);
break;

default:

if (isdigit(postfix[i])) // 执行类似atoi()的功能
{
operand.push(0);

while (isdigit(postfix[i]))
{
operand.push(10 * operand.pop() + postfix[i++] - '0');
}

i--;
}
}

std::cout << operand << std::endl; // 输出堆栈的内容
}

return operand.pop();
}

// 本程序演示了如何后缀表达式和中缀表达式的相互转换,并利用堆栈计算后缀表达式。
// 转换方向:org_infix --> postfix --> infix
int main(int argc, const char *argv[])
{
// const char *org_infix = "(5*(((9+8)*(4*6))+7))"; // section 4.3
const char *org_infix = "(5*((9*8)+(7*(4+6))))"; // exercise 4.12
std::cout << "原始中缀表达式:" << org_infix << std::endl;

char *const postfix = new char[strlen(org_infix) + 1];
infix2postfix(org_infix, postfix);
std::cout << "后缀表达式:" << postfix << std::endl;

char *const infix = new char[strlen(postfix) + 1];
postfix2infix(postfix, infix);
std::cout << "中缀表达式:" << infix << std::endl;

std::cout << "计算结果是:" << postfix_eval(postfix) << std::endl;
std::cout << "计算结果是:" << postfix_eval("5 9*8 7 4 6+*2 1 3 * + * + *") << std::endl; // exercise 4.13

delete []infix;
delete []postfix;
return 0;
}