简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21184 Accepted Submission(s): 7599
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
#include <stack>
#include <stdio.h>
#include <string.h>
using namespace std;
bool check(char,char);
void solve();
char str[205],ch;
double tmp,a,b;
int i,len;
stack<double> v;
stack<char> c;
int main()
{
while(gets(str)!=NULL)
{
if(!strcmp(str,"0"))
{
break;
}
solve();
}
return 0;
}
void solve()
{
len=strlen(str);
for(i=0;i<len;i++)
{
if(str[i]==' ')
{
continue;
}
if(str[i]>='0' && str[i]<='9')
{
tmp=0;
while(str[i]>='0' && str[i]<='9')
{
tmp*=10;
tmp+=str[i]-'0';
i++;
}
v.push(tmp);
}
if(str[i]=='+' || str[i]=='-' || str[i]=='*' || str[i]=='/')
{
if(c.empty())
{
c.push(str[i]);
}else{
ch=c.top();
while(check(ch,str[i]))
{
a=v.top();
v.pop();
b=v.top();
v.pop();
c.pop();
switch(ch)
{
case '+':
v.push(a+b);
break;
case '-':
v.push(b-a);
break;
case '*':
v.push(a*b);
break;
case '/':
v.push(b/a);
break;
}
if(c.empty())
{
break;
}else{
ch=c.top();
}
}
c.push(str[i]);
}
}
}
while(!c.empty())
{
a=v.top();
v.pop();
b=v.top();
v.pop();
ch=c.top();
c.pop();
switch(ch)
{
case '+':
v.push(a+b);
break;
case '-':
v.push(b-a);
break;
case '*':
v.push(a*b);
break;
case '/':
v.push(b/a);
break;
}
}
printf("%.2f\n",v.top());
v.pop();
}
bool check(char ch1,char ch2)
{
if(ch1=='*'||ch1=='/')
{
return true;
}
if(ch2=='+'||ch2=='-')
{
return true;
}
return false;
}