HDU-1237简单计算器
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2
4 + 2 * 5 - 7 / 11
0
Sample Output
3.00
13.36
题目地址
堆栈的运用,借鉴于一下大佬的博客
大佬的博客
以下是我的AC代码
#include <bits/stdc++.h>
using namespace std;
int main(){
stack<double> s;
int n;
double ans=0;
char a;
while(~scanf("%d%c",&n,&a)) //第二个a输入的是空格哦~
{
if(n==0&&a=='\n')
break;
s.push(n); //第一个数入栈
scanf("%c%d",&a,&n); //第一个a是运算符 n为第二个数据
double temp;
//判断区 对第一个运算符进行判断并对数据运算
if(a=='+'){
s.push((double)n);
}
if(a=='-'){
s.push(-(double)n);
}
if(a=='*'){
temp=s.top();
s.pop();
temp=temp*(double)n;
s.push(temp);
}
if(a=='/'){
temp=s.top();
s.pop();
temp=temp/(double)n;
s.push(temp);
}
while(~scanf("%c",&a)){ //这个a为空格或换行符,若为换行符则退出
if (a=='\n')
break;
scanf("%c%d",&a,&n); //这个a为2~n个运算符,n为第3~n个数据
//判断区 对运算符进行判断并对数据进行运算
if(a=='+'){
s.push((double)n);
}
if(a=='-'){
s.push(-(double)n);
}
if(a=='*'){
temp=s.top();
s.pop();
temp=temp*(double)n;
s.push(temp);
}
if(a=='/'){
temp=s.top();
s.pop();
temp=temp/(double)n;
s.push(temp);
}
}
while(!s.empty()){
ans+=s.top();
s.pop();
}
printf("%.2lf\n",ans);//注意题目要求的精确度
ans=0;
}
return 0;
}