表达式求值
来源:互联网 发布:配色软件中文 编辑:程序博客网 时间:2024/04/30 10:07
描述ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)输入第一行输入一个整数n,共有n组测试数据(n<10)。每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。数据保证除数不会为0输出每组都输出该组运算式的运算结果,输出结果保留两位小数。样例输入21.000+2/4=((1+2)*5+1)/4=样例输出1.504.00//标程:#include<stdio.h>#include<iostream>#include<string>#include<stack>using namespace std;stack<double> Calculator1; //存储数字stack<char> Calculator2; //存储运算符int cmp(char str_operator){if(str_operator=='*' || str_operator=='/') return 2;if(str_operator=='-' || str_operator=='+') return 1;if(str_operator=='(') return 0;}void calculate(){char temp=Calculator2.top();Calculator2.pop();double num1=Calculator1.top();Calculator1.pop();double num2=Calculator1.top();Calculator1.pop();if(temp=='+') Calculator1.push(num2+num1);if(temp=='-') Calculator1.push(num2-num1);if(temp=='*') Calculator1.push(num2*num1);if(temp=='/') Calculator1.push(num2/num1);}int main(){ // freopen("a.txt","r",stdin); int n,i;cin>>n;while(n--){string str="";cin>>str; while(!Calculator1.empty()) Calculator1.pop();while(!Calculator2.empty()) Calculator2.pop();double integer=0; //整数部分;double decimal=0; //小数部分;int flag=0,flag1=0;double cnt=1; for(i=0;i<str.size();i++){ if(str[i]=='(' || str[i]==')' || str[i]=='+' || str[i]=='-' || str[i]=='/' || str[i]=='*' || str[i]=='=') { if(flag1) Calculator1.push(integer+decimal); integer=decimal=0; flag=flag1=0; cnt=1; if(str[i]=='=') continue; if(str[i]==')') { while(Calculator2.top()!='(') calculate(); Calculator2.pop(); continue; } if(Calculator2.empty()) Calculator2.push(str[i]); else { if(str[i]=='(') { Calculator2.push(str[i]); continue; } while(!Calculator2.empty() && cmp(Calculator2.top())>=cmp(str[i])) calculate(); Calculator2.push(str[i]); } } else { flag1=1; if(str[i]>='0' && str[i]<='9' && flag==0) integer=integer*10+str[i]-'0'; if(str[i]=='.') flag=1; if(str[i]>='0' && str[i]<='9' && flag==1) { cnt=cnt*0.1; decimal+=(str[i]-'0')*cnt; } }}while(!Calculator2.empty() && Calculator1.size()>=2) calculate(); if(!Calculator1.empty()) printf("%.2lf\n",Calculator1.top());}return 0;}
0 0
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- 表达式求值
- PHP,Mysql日期和时间整理
- Android照片墙应用实现,再多的图片也不怕崩溃
- android开发环境搭建
- python 多媒体框架pyglet开发
- MathDemo
- 表达式求值
- 揪出口臭十大罪魁祸首
- shell多行注释
- 批处理学习(三)
- 项目一(2)。不用参数默认构造函数
- 重构改善既有代码的设计--重构第一个案例
- C++并发实战:面试题3:一道google笔试题
- 海里数据处理面试题中的一些概念介绍
- 李白打酒