• 杭电1237--简单计算器 (getchar() + 栈)


    简单计算器

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


    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
     
    //getchar(); 较难理解;定义一个栈;存储处理后的数据;最后把栈中所有元素相加;
     
    #include <stdio.h>
    #include<stack>
    using namespace std;
    int main()
    {
        double m,n; char ch;
        while(~scanf("%lf",&m))
        {
            if(getchar() == '
    ' && m == 0 )   //位置固定;
            break ;
            stack <double> s;
            s.push(m) ;
            scanf("%c",&ch);          //执行一次; 
            while(~scanf("%lf",&m))
            {
                if(ch == '*')
                {
                    n=s.top() ;
                    n*=m ;
                    s.pop() ;
                    s.push(n) ;
                }
                
                if( ch == '/')
                {
                    n=s.top() ;
                    n/=m ;
                    s.pop() ;
                    s.push(n) ; 
                }
                
                if(ch == '+')
                s.push(m) ;
                
                if(ch == '-')
                s.push(-m) ;
                if(getchar() == '
    ')
                break;
                //ch=getchar();     //gethchar() ; 相当于输入一个人字符;
                scanf("%c",&ch); 
            }
            double total =0;
            while(!s.empty())
            {
                total+=s.top() ;
                s.pop() ;
            } 
            printf("%.2lf
    ",total);    
        }    
        return 0;
    }
     
     
  • 相关阅读:
    修改spring boot 启动logo
    查看jvm常用命令
    intellij IDEA破解
    hdu 新生晚会
    How many prime numbers(素数)
    2077 汉诺塔IV
    Factorial
    双人黑白块
    EasyX
    七夕情人节
  • 原文地址:https://www.cnblogs.com/soTired/p/4612278.html
Copyright © 2020-2023  润新知