// 将字符转换成数字
double readNumber(char c[],int *i)
{
double x = 0.0;
int k = 0;
while (c[*i] >= '0' && c[*i] <= '9')
x = x*10 + (c[(*i)++] - '0');
if(c[*i] == '.')
{
(*i)++;
while (c[*i] >= '0' && c[*i] <= '9')
{
x = x*10 + (c[(*i)++] - '0');
k++;
}
}
while (k != 0)
{
x = x/10.0;
k--;
}
return x;
}
// 后缀表达式求值
double cal(char c[])
{
double op[MAX_SIZE] = {}; // 操作数栈
int top = 0; // 栈顶指针
double left,right; // 左、右操作数
int i = 0;
while (c[i])
{
if(c[i] >= '0' && c[i] <= '9')
op[top++] = readNumber(c,&i);
else if(c[i] == ' ') i++;
else
{
right = op[--top];
left = op[--top];
if(c[i] == '+')
op[top++] = left + right;
else if(c[i] == '-')
op[top++] = left - right;
else if(c[i] == '*')
op[top++] = left * right;
else
op[top++] = left / right;
i++;
}
}
return op[--top];
}
int main()
{
char c[] = "6/3+(5*6-2*7)/4";
char r[MAX_SIZE]={};
convert(c,r);
int i=0;
while (r[i])
printf("%c",r[i++]);
printf("\n");
printf("%f",cal(r));
return 0;
}
版权属于:
lixiangrong
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论 (0)