多项式表达求值,已有加减乘除功能,可以循环输入,还需增添判断表达式是否合法(只是被除数不为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//符号
{
{
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的时候,会出现不正常的结果
[解决办法]
解析输入的表达式,会用到栈的知识来实现,或者树