简单计算器
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
#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; } |