读书人

多项式表述求值已有加减乘除功能可

发布时间: 2013-07-11 15:38:46 作者: rapoo

多项式表达求值,已有加减乘除功能,可以循环输入,还需增添判断表达式是否合法(只是被除数不为0)的功能以及乘方功能
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<math.h>
#define maxn 1001
//const int maxn=1001;
struct NumStack//数字
{
double stack;
int top;
}numstack;
struct OpStack//符号
{


char stack;
int top;
}opstack;
char rpn;
int GetLevel(char op)//优先级
{
if(op=='^')
return 3;
if(op=='*'||op=='/')
return 2;
if(op=='+'||op=='-')
return 1;
return 0;
}
double Add(double a, double b)
{
return a+b;
}
double Sub(double a, double b)
{
return a-b;
}
double Mul(double a, double b)
{
return a*b;
}
double Div(double a, double b)
{
return a/b;
}
double Pow(double a, double b)
{
// double s=1.0;
//for(int i=0;i<b;i++)
//s=s*a;
//return s;
double s;
s=pow(a, b);
return s;
}
double Caculate(double a, double b, char op)
{
switch(op)
{
case '+':return Add(a,b);
case '-':return Sub(a,b);
case '*':return Mul(a,b);
case '/':return Div(a,b);
case '^':return Pow(a,b);
}
}
void GetRpn(char *str)
{
int cou=0;//计数
int isnum=0;//判断是否是数字
opstack.top=0;//初始化
int i = 0;
if(str=='-')
{
if(str=='-')
{
rpn='0';
rpn='#';
}
}
for(;i<strlen(str);i++)
{
if(str>='0'&&str<='9'||str=='.')


{

isnum=1;
rpn=str;
}
else
{
if(isnum)
{
rpn='#';
isnum=0;
}
if(str=='=')
break;
else if(str=='(')
{
if(str=='-')
{
rpn='0';
rpn='#';
}
opstack.stack=str;
}
else if(opstack.top==0)
opstack.stack=str;
else if(str==')')
{
while(opstack.stack!='(')
rpn=opstack.stack;
opstack.top--;
}
else if(GetLevel(str)<=GetLevel(opstack.stack))
{


while(opstack.top>0&&GetLevel(str)<=GetLevel(opstack.stack))
rpn=opstack.stack;
opstack.stack=str;
}
else
opstack.stack=str;
}
}
while(opstack.top)
rpn=opstack.stack;
rpn='\0';

}
double GetAns(char *str)
{
int negative=0;
numstack.top=0;

for(int i=0; i<strlen(str);i++)
{
if(str=='$')
negative=1;
else if(str>='0'&&str<='9')//
{
double ita=0,now=10;
int flag=0;
for(;str!='#';i++)
{
if(str=='.')
{
flag=1;
i++;
}
if(flag==0)
{
ita=ita*10+str-'0';
}
else


{
ita+=(str-'0')/now;
now*=10;
}
}
numstack.stack=ita;
}
else
{
double a=numstack.stack;
double b=numstack.stack;
double c=Caculate(b,a,str);
numstack.stack=c;

}
}
return numstack.stack; //return numstack.stack;

}
int main()
{
char str;
int i=0, n, count=0;
scanf("%d", &n);
while(scanf("%s", &str)!=EOF)
{
GetRpn(str);
printf("%s\n", rpn);
//if(rpn=='#0#/')
// printf("Error!");
count++;
printf("Case #%d: %.2lf\n", count,GetAns(rpn));
i++;
if(i>=n)
break;
}


return 0;
}

C 多项式计算
[解决办法]
建议啊.
1.括号啊.
2.贴代码请加 插入代码啊.
3.注释啊.

[解决办法]
增添判断表达式是否合法

这个是需要,不然当你出现除0的时候,会出现不正常的结果
[解决办法]
解析输入的表达式,会用到栈的知识来实现,或者树

读书人网 >C语言

热点推荐