前提:
1,参与运算的数值为0-9的个位数
2,没有包含括号
3,输入的表达式是正确的
4,除法进行的是整除运算
代码:
long calc(char *str)
{
long fst,snd,trd,idx=0;
char fop,nop;
fst=str[0]-48;
fop=str[++idx];
snd=str[++idx]-48;
do
{
nop=str[idx+1];
if(fop=='+'||fop=='-')
{
if(nop=='+'||nop=='-'||nop=='\0')
{
switch(fop)
{
case '+':fst+=snd;break;
case '-':fst-=snd;break;
case '*':fst*=snd;break;
case '/':fst/=snd;break;
}
if(nop=='\0')
break;
fop=str[++idx];
snd=str[++idx]-48;
}
else if(nop=='*'||nop=='/')
{
idx+=2;
trd=str[idx]-48;
snd=nop=='*'?snd*trd:snd/trd;
}
}
else if(fop=='*'||fop=='/')
{
fst=fop=='*'?fst*snd:fst/snd;
fop=str[++idx];
snd=str[++idx]-48;
}
else
{
break;
}
}
while(1);
return fst;
}
演示:
6+8-3*4/2=8 4*5/2-9+5=6 1+2-3-4+5=1 4*2*3*9*5=1080 4*2*3-9+5/2=17 4+2-3*9/7+5-2=6