HDOJ 1237 简单计算器(栈)

来源:互联网 发布:php是后端还是前端 编辑:程序博客网 时间:2024/06/05 16:25

简单计算器

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


Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
 

Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
 

Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
 

Sample Input
1 + 24 + 2 * 5 - 7 / 110
 

Sample Output
3.0013.36
 

Source
浙大计算机研究生复试上机考试-2006年
 

Recommend
JGShining   |   We have carefully selected several similar problems for you:  1230 1235 1236 1233 1232
思路:利用两个栈,一个存double数字,一个存char运算符,比如 4 + 2 * 5 - 7 / 11 ,遇到空格略过,遇到字符型数字转换成double数字并存栈,遇到运算符:  1. 要运算并清空两栈的情况:是+或-(运算并清空) &&&&&是*或/,并且其前的运算符栈内符号为*或/,按优先级来说就应该先计算前一个*或/(运算)。  2.运算符先存入栈的情况:是 *或 /,并且其前的运算符栈内符号不为*或 /。别忘了最后的最后要清空栈。
清楚思想请看:http://blog.csdn.net/jinjide_ajin/article/details/47108889
AC代码,有一些很需要注意的地方都标记上了:


#include<cstdio>#include<cstring>#include<stack>using namespace std;stack <double> num;//数字栈stack <char> sta;//字符栈double math(char c){//变量为识别的运算符    double a,b;//结果    a=num.top(); num.pop();    b=num.top(); num.pop();    switch(c){        case '*': return b*a;        case '/': return b/a;        case '+': return b+a;        case '-': return b-a;    }//注意这里 a,b 顺序不能反}//只进行一次运算int main(){    char oper,str[210];    int len,i;    double nnum;    memset(str,0,sizeof(str));    while(gets(str)&&strcmp(str,"0")!=0){        len=strlen(str);        /********************** for *******************/        for(i=0;i<len;i++){            while(str[i]==' ') i++;  //略过空格            /************下面为转换数字**********/            nnum=0;            while(str[i]>='0'&&str[i]<='9'&&i<len){                nnum=nnum*10+str[i]-'0';                i++;            } //将数字由char转换为double            num.push(nnum); //数字进栈            /************下面为略过空格**********/            while(str[i]==' ') i++;//略过空格            /************下面为判断操作符**********/            if(str[i]=='+'||str[i]=='-'){                while(!sta.empty()){                    num.push(math(sta.top()));                    sta.pop();                }                sta.push(str[i]);            }//运算符为‘+’,‘-’就清栈            else if(str[i]=='*'||str[i]=='/'){                if(!sta.empty()&&(sta.top()=='*'||sta.top()=='/')){                    num.push(math(sta.top()));                    sta.pop();                }                sta.push(str[i]);            }//运算符为‘*’,‘/’时,先判断前方是否是‘*’,‘/’,若是就按运算顺序算前一个运算符,否者此运算符进栈        }        /*********************** for *************************/        while(!sta.empty()){                nnum=math(sta.top());                sta.pop();                num.push(nnum);            }//清空剩余栈            printf("%.2lf\n",num.top());            num.pop();            memset(str,0,sizeof(str));    }    return 0;}

转载请注明出处:http://blog.csdn.net/jinjide_ajin/article/details/47186649

 
0 0
原创粉丝点击