简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 23232 Accepted Submission(s): 8402
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
Source
Recommend
JGShining
题意:中文题。
思路:在这个计算器中*和/的优先级比+和-的优先级高,所以会优先算这些运算符。而算完之后原来的式子中就只会含有+和-,所以最后只要将这些数相乘就行了。
用两个栈来存,一个存运算符,一个存数字。当遇到一个数字的时候,如果运算符栈不为空,那么看运算符栈顶是什么元素。1:为+,则将该数压入数字栈。
2:为-,将该数相反数压入数字栈。
3:为*,将数字栈栈顶取出并弹出,将两数乘积压入数字栈。
4:为/,将数字栈顶取出并弹出,将两数的商压入数字栈。
然后弹出运算符栈顶。一直这样操作最后把数字栈的所有元素相加就行了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
char str[205];
int main()
{
while(gets(str)!=NULL)
{
stack<char> sta1;
stack<double> sta2;
if(strcmp(str,"0")==0)
break;
int len=strlen(str);
for(int i=0;i<len;)
{
if(str[i]==' ')
{
i++;
continue;
}
else if(str[i]=='*'||str[i]=='/'||str[i]=='-'||str[i]=='+')
{
sta1.push(str[i]);
i++;
}
else
{
double num=0;
while(str[i]!=' '&&str[i]!='\0')//读入
{
num=num*10+str[i]-'0';
i++;
}
if(!sta1.empty())
{
char c=sta1.top();
sta1.pop();
if(c=='*')
{
double num2=sta2.top();
sta2.pop();
num=num2*num;
}
else if(c=='/')
{
double num2=sta2.top();
sta2.pop();
num=num2/num;
}
else if(c=='-')
{
num=-num;
}
}
sta2.push(num);
}
}
double sum=0;
while(!sta2.empty())
{
sum+=sta2.top();
sta2.pop();
}
printf("%.2lf\n",sum);
}
return 0;
}