永发信息网

C语言:任意算术表达式的求值

答案:4  悬赏:20  手机版
解决时间 2021-06-01 11:10
  • 提问者网友:谁的错
  • 2021-05-31 11:35

要程序代码

最佳答案
  • 五星知识达人网友:雪起风沙痕
  • 2021-05-31 11:58
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <setjmp.h>

jmp_buf jmpenv;

double opdstack[100];
char optstack[100];
double* sp1 = opdstack;
char* sp2 = optstack;
#define OPD sp1
#define OPT sp2
#define PUSH( s, n ) (*s++ = n)
#define POP( s ) (*--s)
#define TOP( s ) (*(s-1))
#define V( s ) ((void*)(s))
#define EMPTY( s ) ( V(s) == V(sp1) ? V(s) == V(opdstack) : V(s) == V(optstack) )
#define SIZE( s ) ( (double*)s == sp1 ? (double*)s - opdstack : (char*)s - optstack )

int getpred( char c )
{
char* pred[] = { "0123456789","+-", "*/", "()" };
int i = 0;
for ( i = 0; i < 3; ++i )
if ( strchr( pred[i], c ) != NULL )
break;
return i;
}

void initerror()
{
int r;
switch( r = setjmp( jmpenv ) )
{
case 1: puts( "invalid operator combination." ); break;
case 2: puts( "invalid character." ); break;
case 3: puts( "expression is not valid." ); break;
}
if ( r ) exit( 0 );
}

void docal()
{
double a, b;
char c;
b = POP( OPD );a = POP( OPD );c = POP( OPT );
switch( c )
{
case '+': a += b; break;
case '-': a -= b; break;
case '*': a *= b; break;
case '/': a /= b; break;
default: longjmp( jmpenv, 1 );
}
PUSH( OPD, a );
}

double eval( char* expr )
{
char* fwd = expr;
int n;
double num;
while( *fwd ) {
switch( getpred( *fwd ) )
{
case 0:
sscanf( fwd, "%lf%n", &num, &n );
fwd += n;
PUSH( OPD, num );
if ( *fwd == '(' )
longjmp( jmpenv, 1 );
break;
case 1: case 2:
while( TOP( OPT ) != '(' && SIZE( OPD ) > 1 && getpred( *fwd ) <= getpred( TOP( OPT ) ) )
docal();
PUSH( OPT, *fwd );
++fwd;
break;
case 3:
if ( *fwd == '(' ) {
PUSH( OPT, *fwd );
} else {
while( TOP(OPT) != '(' )
docal();
POP( OPT );
}
++fwd;
break;
default:
longjmp( jmpenv, 2 );
exit( 0 );
break;
}
}
while ( !EMPTY( OPT ) )
docal();
num = POP( OPD );
if( !( EMPTY( OPT ) && EMPTY( OPD ) ) )
longjmp( jmpenv, 3 );
return num;
}

int main()
{
initerror();
char a[100] = "2*12+((1+2)/3)*(3-4/4)";
printf( "example:\n%s=%g\n\n", a, eval( a ) );
printf( "please input a valid expr:\n" );
gets( a );
printf( "%s=%g\n", a, eval( a ) );
}
全部回答
  • 1楼网友:末日狂欢
  • 2021-05-31 14:32

//表达式求值 //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 表达式求值实现函数 // ////////////////////////////////////////////// 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 '='; } 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; } bool In(char c,char op[]) { for (int i = 0;i<7;i++) { if (op[i] == c) return true; } return false; } 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; }

const int STACK_INIT_SIZE = 100; // 初始分配的长度 const int STACKINCREMENT = 10; // 分配内存的增量 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; }

void DestroyStack(SqStack *S) { assert(S != NULL);

free(S->base); S->top = S->base = NULL; }

bool StackEmpty(SqStack S) { assert((S.base != NULL) && (S.top != NULL)); return(S.base == S.top); }

int StackLength(SqStack S) { assert((S.base != NULL) && (S.top != NULL)); return(S.top-S.base); }

ElemType GetTop(SqStack S, ElemType *e) { assert((S.base != NULL) && (S.top != NULL)); if(StackEmpty(S)) return false;

*e = *(S.top-1); return *e; }

void StackTraverse(SqStack S, void (*fp)(ElemType)) { assert((S.base != NULL) && (S.top != NULL)); for(; S.base<S.top; S.base++) (*fp)(*S.base); }

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; }

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

  • 2楼网友:街头电车
  • 2021-05-31 14:14

一看你就是个菜鸟!

哥来回答

要实现输入任意表达式求值

楼上的的确不错 但是那是数据结构的 对于你们菜鸟来说 学习那还是早了点

我来编写一道简单的题目吧:

#include<stdio.h>

void main()

{

double a,b,result;//定义两个操作数

char opr;//定义算法

printf("please input first number:");//输入第一个数

scanf("%lf",&a);

printf("操作方法:");//输入符号

scanf("%c",&opr);

printf("please input second number:");//输入第二个数

scanf("%lf",&b);

if (opr=='+')

result=a+b;

else if(opr=='-')

result=a-b;

else if(opr=='/')

result=a/b;

else if(opr=='*')

result=a*b;

printf("运算结果是:%lf",result);

}

好了 OK 给我加分吧!

  • 3楼网友:末日狂欢
  • 2021-05-31 12:46
表达式末尾加要加# 例如5+6要打5+6# #include<cstdio> #include<malloc.h> #define NULL 0 typedef struct node{ char date; struct node *next; }SNode; SNode *InitStack(){ SNode *top; top=(SNode *)malloc(sizeof(SNode)); top->next=NULL; return top; } void PushOptr(SNode *top,char x){ SNode *p; p=(SNode *)malloc(sizeof(SNode)); p->date=x; p->next=top->next; top->next=p; } char PopOptr(SNode *top){ SNode *p; char x; if(top==NULL) return NULL; p=top->next; x=p->date; top->next=p->next; free(p); return x; } void PushOpnd(SNode *top,char x){ SNode *p; p=(SNode *)malloc(sizeof(SNode)); p->date=x; p->next=top->next; top->next=p; } char PopOpnd(SNode *top){ SNode *p; char x; if(top==NULL) return NULL; p=top->next; x=p->date; top->next=p->next; free(p); return x; } char GetTop(SNode *top){ return (top->next)->date; } int In(char c){ int n; switch(c){ case '+': case '-': case '*': case '/': case '(': case ')': case '#':n=1;break; default:n=0;break; } return n; } char Precede(char x,char y){ int i,j; int form[7][7]={{1,1,-1,-1,-1,1,1},{1,1,-1,-1,-1,1,1},{1,1,1,1,-1,1,1},{1,1,1,1,-1,1,1},{-1,-1,-1,-1,-1,0,2},{1,1,1,1,2,1,1},{-1,-1,-1,-1,-1,2,0}}; switch(x){ case '+':i=0;break; case '-':i=1;break; case '*':i=2;break; case '/':i=3;break; case '(':i=4;break; case ')':i=5;break; case '#':i=6;break; } switch(y){ case '+':j=0;break; case '-':j=1;break; case '*':j=2;break; case '/':j=3;break; case '(':j=4;break; case ')':j=5;break; case '#':j=6;break; } if(form[i][j]==1) return '>'; else if(form[i][j]==-1) return '<'; else return '='; } int Operate(char x,char z,char y){ int a=x-'0',b=y-'0'; switch(z){ case '+':return a+b; case '-':return a-b; case '*':return a*b; case '/':return a/b; } } char Eval_Exp(){ char a,b,c,r,f,z; int result; SNode *top[2]; top[0]=InitStack(); PushOptr(top[0],'#'); top[1]=InitStack(); c=getchar(); while(c!='#'||(GetTop(top[0]))!='#'){ if(!In(c)){ PushOpnd(top[1],c); c=getchar(); } else{ r=Precede(GetTop(top[0]),c); switch(r){ case '<':PushOptr(top[0],c); c=getchar(); break; case '=':PopOptr(top[0]); c=getchar(); break; case '>':b=PopOptr(top[0]); a=PopOpnd(top[1]); z=PopOpnd(top[1]); result=Operate(z,b,a); f=result+'0'; PushOpnd(top[1],f); break; } } } return f; } void main(){ char result; result=Eval_Exp(); printf("%d\n",result-'0'); }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯