+关注继续查看

简单计算器

Problem Description

Input

Output

Sample Input

1 + 2 4 + 2 * 5 - 7 / 11 0

Sample Output

3.00 13.36

Source

#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
int compare_opr[4][4]=
{
0,0,-1,-1,
0,0,-1,-1,
1,1,0,0,
1,1,0,0
};
int opr_tonum(char x)
{
switch(x)
{
case '+':
return 0;
break;
case '-':
return 1;
break;
case '*':
return 2;
break;
case '/':
return 3;
break;
}

}
int isnum(char x)
{
if(x>='0'&&x<='9')
return 1;
else   return 0;
}
int chartonum(char x)
{
return x-'0';
}
void caculate( stack<double>&num_stack , stack<char>&opr_stack)
{
double num_A,num_B;
char temp;
num_A=num_stack.top();
num_stack.pop();
num_B=num_stack.top();
num_stack.pop();
temp=opr_stack.top();
opr_stack.pop();
switch(opr_tonum(temp))
{
case 0:
return num_stack.push(num_A+num_B) ;
break;
case 1:
return num_stack.push(num_B-num_A)   ;
break;
case 2:
return num_stack.push(num_A*num_B)   ;
break;
case 3:
return num_stack.push(num_B/num_A)   ;
break;
}
}
int main()
{
char str[205];
while(cin.getline(str,205))
{
if(str[0]=='0'&&str[1]=='\0')
break;
else
{
int index=0;
stack<char>opr_stack;
stack<double>num_stack;
while(str[index]!='\0')
{
if(str[index]==' ')
{
index++;
continue;
}
else
{
if(isnum(str[index]))
{
double num=0.0;
do
{
num*=10;
num +=chartonum(str[index]);
index++;
}
while(isnum(str[index]));
num_stack.push(num);
}
else
{
if(opr_stack.empty())
{
opr_stack.push(str[index]);
index++;
continue;
}
else
{
int i,j;
i=opr_tonum(str[index]);
j=opr_tonum(opr_stack.top());
switch(compare_opr[i][j])
{
case 1:
opr_stack.push(str[index]);
index++;
break;
case 0:
case -1:
caculate(num_stack,opr_stack);
break;
}
}
}
}
}
while( !num_stack.empty() && !opr_stack.empty() )
caculate( num_stack , opr_stack ) ;
double Output ;
Output = num_stack.top() ;
printf("%.2f\n",Output);
}
}
return 0;
}

HDU1862

930 0
hdu 3724 Encoded Barcodes

678 0
hdu 1712 ACboy needs your help
ACboy这学期有N门课程，他计划花最多M天去学习去学习这些课程，ACboy再第i天学习第j门课程的收益是不同的，求ACboy能获得的最大收益。
0 0
hdu2084数塔

439 0
+关注
JKXQJ