HDU 1237
给出几组测试数据:
发现数据比较严格:
1.
20 + 0
答案是 20 而不是结束
2.
10 / 5 / 2
答案是 1 而不是 4
基本上这样算是通过了。。。基本思路重要是如何处理运算符的优先值问题。
给出几个不同的输入方式
1. gets(); 一次性输入,有长度控制循环。
#include <iostream>
#include<stack>
#include<cstring>
using namespace std;
stack <char> ststr;
stack <double>stnum;
void Calculation()
{
double a,b;
a = stnum.top() ;
stnum.pop();
b = stnum.top() ;
stnum.pop();
switch(ststr.top() )
{
case '+': stnum.push(a+b);break;
case '-': stnum.push(b-a);break;
case '*': stnum.push(a*b);break;
case '/': stnum.push(b/a);break;
}
ststr.pop();
}
int check( char a ) //自己定义了一个优先级
{
char b = ststr.top();
int l,r;
switch(a)
{
case '#': l = 0;break;
case '(': l = 0;break;
case ')': l = 0;break;
case '+': l = 1;break;
case '-': l = 1;break;
case '*': l = 2;break;
case '/': l = 2;break;
}
switch(b)
{
case '#': r = 0;break;
case '(': r = 0;break;
case ')': r = 0;break;
case '+': r = 1;break;
case '-': r = 1;break;
case '*': r = 2;break;
case '/': r = 2;break;
}
if(l>r)
{
ststr.push(a);
return 1;
}
else if( l == r && a == '#')
{
return 1;
}
else
{
Calculation();
return 0;
}
}
int main()
{
int i,j,n,leng;
double sum;
char str[210];
while(1)
{
gets(str);leng = strlen(str);
if(str[0] == '0' && leng == 1)break;
str[leng] = '#';
str[leng+1] = '\0';
ststr.push('#') ;
for(i = 0;i<=leng;)
{
if(str[i] >= '0' && str[i] <='9' )
{
sum =0;
while(str[i] >= '0' && str[i] <='9' )
{
sum = sum*10 + str[i]-'0';
i++;
}
stnum.push(sum);
if(str[i] == '#')
{
while(check('#') == 0); //注意循环!防止计算没有结束!
printf("%.2lf\n",stnum.top() );
stnum.pop();
}
i++;
}
else
{
if(check(str[i]))
{ i++;i++;
}
}
}
}
}
2. scanf() 一对一对的输入,时刻检测 '\n'字符;
#include <iostream>
#include<stack>
#include<cstring>
using namespace std;
stack <char> ststr;
stack <double>stnum;
void Calculation()
{
double a,b;
a = stnum.top() ;
stnum.pop();
b = stnum.top() ;
stnum.pop();
switch(ststr.top() )
{
case '+': stnum.push(a+b);break;
case '-': stnum.push(b-a);break;
case '*': stnum.push(a*b);break;
case '/': stnum.push(b/a);break;
}
ststr.pop();
}
int check( char a ) //自己定义了一个优先级
{
char b = ststr.top();
int l,r;
switch(a)
{
case '#': l = 0;break;
case '(': l = 0;break;
case ')': l = 0;break;
case '+': l = 1;break;
case '-': l = 1;break;
case '*': l = 2;break;
case '/': l = 2;break;
}
switch(b)
{
case '#': r = 0;break;
case '(': r = 0;break;
case ')': r = 0;break;
case '+': r = 1;break;
case '-': r = 1;break;
case '*': r = 2;break;
case '/': r = 2;break;
}
if(l>r)
{
ststr.push(a);
return 1;
}
else if( l == r && a =='#')
{
return 1;
}
else
{
Calculation();
return 0;
}
}
int main()
{
int i,j,n,leng;
int num;
char str;
ststr.push('#') ;
int f = 0;
while( scanf("%d%c",&num,&str) )
{
if(f == 0 && num == 0 && str == '\n')break;
else if(((num == 0 && f== 1 ) || num!=0)&& str == '\n')
{
stnum.push(num) ;
while(check('#') == 0); //注意循环
printf("%.2lf\n",stnum.top());
stnum.pop();
f = 0;
}
else
{
f = 1;
scanf("%c ",&str);
stnum.push(num) ;
while(check(str) == 0); //注意循环
}
// printf("%lf\n",sum);
}
}