题目:简单计算器
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例:
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
思路:利用栈,创建两个栈,一个是用来存数的,一个用来存运算符的,因为运算符之间是有优先级关系,所以要定义一个函数用来判断其优先级,当后来即将存的优先级高于栈顶的,则将其存入栈顶,如果后来的优先级是低于栈顶的,则要让运算符的栈的栈顶与存数的栈的前两个,进行运算,然后把结果再存入存数的栈顶。依次这样,最后存数的栈剩下的那个栈顶就是最后的结果;
新技巧:1:这里是栈的一种新的用法,即关于优先级问题的处理,可以通过满足其优先级关系就进栈,不满足则进行一系列操作,就是说有关优先级的问题可以考虑用栈来处理;
2:关于优先级的问题,如果无法用数值等来比较,则自己定义函数来将优先级排出来,如果很杂的时候,在情况不多的时候可以一个一个情况列出来;
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node {
double val;
char ch;
Node *next;
};
struct stacks{
Node *top;
Node *bottom;
};
int compere(char ch1,char ch2);
double sumulete (double a,double b,char x);
int main()
{
double sum,b1,b2,b3;
int tag,i,num;
char ch,a[205];
while(gets(a)!=NULL)
{
if(strcmp(a,"0")==0)
break;
stacks *st_number=(stacks *)malloc(sizeof(stacks ));
st_number->top=(Node *)malloc(sizeof(Node ));
st_number->top->next=nullptr;
st_number->bottom=st_number->top;
stacks *st_sign=(stacks *)malloc(sizeof(stacks ));
st_sign->top=(Node *)malloc(sizeof(Node ));
st_sign->top->ch='#';
st_sign->top->next=nullptr;
st_sign->bottom=st_sign->top;
tag=0;sum=0;num=strlen(a);
for(i=0;i<=num;i++)
{
if(a[i]==' ')
continue;
else if(a[i]<='9'&&a[i]>='0')
{
sum=sum*10+a[i]-'0';
tag=1;
}
else
{
if(tag)
{
Node *temp=(Node *)malloc(sizeof(Node ));
temp->val=sum;
temp->next=st_number->top;
st_number->top=temp;
tag=0;sum=0;
}
if(compere(st_sign->top->ch,a[i])<0)
{
Node *temp=(Node *)malloc(sizeof(Node ));
temp->ch=a[i];
temp->next=st_sign->top;
st_sign->top=temp;
}
else if(compere(st_sign->top->ch,a[i])>0)
{
b1=st_number->top->val;
Node *tt=st_number->top;
st_number->top=tt->next;
free(tt);
b2=st_number->top->val;
b3=sumulete(b1,b2,st_sign->top->ch);
st_number->top->val=b3;
Node *ss=st_sign->top;
st_sign->top=ss->next;
free(ss);
i--;
}
else
{
Node *tt=st_sign->top;
st_sign->top=tt->next;
free(tt);
}
}
}
printf("%.2f\n",st_number->top->val);
}
return 0;
}
double sumulete (double a,double b,char x)
{
double t;
switch(x)
{
case '*':t=a*b;break;
case '/':t=b/a;break;
case '+':t=a+b;break;
case '-':t=b-a;break;
}
return t;
}
int compere(char ch1,char ch2)
{
int tag;
if(ch2=='\0')
{
if(ch1=='#')
tag=-1;
else
tag=1;
}
else if(ch1=='+'||ch1=='-')
{
if(ch2=='+'||ch2=='-'||ch2==')')
tag=1;
else
tag=-1;
}
else if(ch1=='*'||ch1=='/')
{
if(ch2=='(')
tag=-1;
else
tag=1;
}
else if(ch1=='(')
{
if(ch2==')')
tag=0;
else
tag=-1;
}
else if(ch1==')')
tag=1;
else if(ch1=='#')
tag=-1;
return tag;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。