HDU 1237 简单计算器

http://acm.hdu.edu.cn/showproblem.php?pid=1237

简单计算器

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13928    Accepted Submission(s): 4642


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
浙大计算机研究生复试上机考试-2006年
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:   1230  1235  1234  1236  1229 
 
都用double类型,并且用C++提交  否者wa、、 有小数的就得边扫描边计算。
 

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#include <stack>
#define maxn 10000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
#define INF 1<<30
const ull inf = 1LL << 61;
const double eps=1e-5;

using namespace std;

bool cmp(int a,int b)
{
return a>b;
}
char a[1100];
char b[1100];
char p[1100];
stack<char>s;
double val(char x){
switch(x){
case '+':
case '-':return 1.0;
case '*':
case '/':return 2.0;
case '(':return 0.0;
default: return -1.0;
}
}
double cal(double x,double y,char c){
switch(c){
case '+':return y+x;
case '-':return y-x;
case '*':return y*x;
case '/':return y/x;
}
}
stack<double>t;
char ss[1000];
double d,x,y;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
s.push('#');
while(gets(ss)){
cle(a),cle(b);
if(ss[0]=='0'&&strlen(ss)==1)break;
int z=0;
for(int i=0;i<strlen(ss);i++)
if(ss[i]!=' ')a[z++]=ss[i];
int m=strlen(a),i,j=0;
for(i=0;i<m;i++){
if(a[i]<='9'&&a[i]>='0'||a[i]=='.'){
int k=0;
cle(p);//此处必清零
while(a[i]<='9'&&a[i]>='0'||a[i]=='.'){
b[j++]=a[i];
p[k++]=a[i++];
}
i--;
d=atof(p);
t.push(d);
}
else if(a[i]=='('){
s.push(a[i]);
}
else if(a[i]==')'){
while(s.top()!='('){
b[j++]=s.top();
x=t.top();t.pop();
y=t.top();t.pop();
d=cal(x,y,b[j-1]);
t.push(d);
s.pop();
}
s.pop();
}
else{
while(val(s.top())>=val(a[i])){
b[j++]=s.top();
x=t.top();t.pop();
y=t.top();t.pop();
d=cal(x,y,b[j-1]);
t.push(d);
s.pop();
}
s.push(a[i]);
}
}
while(s.top()!='#'){
b[j++]=s.top();
x=t.top();t.pop();
y=t.top();t.pop();
d=cal(x,y,b[j-1]);
t.push(d);
s.pop();
}
printf("%.2lf\n",t.top());
while(!t.empty())t.pop();
while(s.top()!='#')s.pop();
}
return 0;
}


你可能感兴趣的:(HDU 1237 简单计算器)