hdoj 1237 简单计算器

来源:互联网 发布:羊肉 知乎 编辑:程序博客网 时间:2024/05/18 01:12

简单计算器

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


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

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

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

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

Sample Output
3.0013.36
堆栈。。。
 
c语言过:
 
#include<stdio.h>#include<string.h>double num[220];int main(){    int i,j,t;    double b,c,sum;    char ch;//运算符号     char kongge;//键入空格     while(scanf("%lf",&b)!=EOF)    {        t=0;        memset(num,0,sizeof(num));        kongge=getchar();//空格         if(b==0&&kongge=='\n')//判断         break;        num[t++]=b;        scanf("%c",&ch);//运算符号         kongge=getchar();//空格         while(scanf("%lf",&b)!=EOF)        {            if(ch=='*')            {                c=num[t-1];                c*=b;                num[t-1]=c;            }            else if(ch=='/')            {                c=num[t-1];                c/=b;                num[t-1]=c;            }            else if(ch=='+')            num[t++]=b;            else if(ch=='-')            num[t++]=-b;            kongge=getchar();//键入空格             if(kongge=='\n')//判断             break;            scanf("%c",&ch);//输入运算符号         }        sum=0;        for(i=0;i<t;i++)        sum+=num[i];        printf("%.2lf\n",sum);    }    return 0;}

c++:
 
#include<stdio.h>#include<stack>using namespace std;int main(){    double b,c,sum;    char ch;    char kongge;     while(scanf("%lf",&b)!=EOF)    {        kongge=getchar();        if(b==0&&kongge=='\n')        break;        stack<double>num;        num.push(b);        scanf("%c",&ch);        while(scanf("%lf",&b)!=EOF)        {            if(ch=='*')            {                c=num.top();                c*=b;                num.pop();                num.push(c);            }            else if(ch=='/')            {                c=num.top();                c/=b;                num.pop();                num.push(c);            }            else if(ch=='+')            num.push(b);            else if(ch=='-')            num.push(0-b);            kongge=getchar();            if(kongge=='\n')            break;            scanf("%c",&ch);        }        sum=0;        while(!num.empty())        {            sum+=num.top();            num.pop();        }        printf("%.2lf\n",sum);    }    return 0;}

 
0 0