online_judge_1019

183 篇文章 0 订阅
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
//#include <iomanip>
#include <stdio.h>

using namespace std;

bool Pri(char a, char b)
{
    if((a=='*'||a=='/')&&(b=='+'||b=='-'))
        return true;
    return false;
}
double Cal(double x, double y, int c)
{
    double re;
    if(c == '+')
        re = x + y;
    else if(c == '-')
        re = x - y;
    else if(c == '*')
        re = x * y;
    else
        re = x / y;
    return re;
}
int main()
{
    string str;
    int data[102];
    char c[102];
    char ch;
    stack<char> op;
    stack<double> da;
    int i,t,k;
    int len;
    double x,y,z;
    while(getline(cin,str))
    {
        if(str == "0")
            break;
        len = str.size();
        for(i=0; i<101; ++i)
        {
            data[i] = 0;
            c[i] = 0;
        }
        k=0;
        for(i=0; i<len; ++i)
        {
            if(isdigit(str[i]))
            {
                t = str[i] - '0';
                data[k] = data[k]*10 + t;
            }
            else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
            {
                c[k] = str[i];
                k++;
            }
        }
        if(k == 0)
        {
            cout<<str<<endl;
            continue;
        }
        da.push(data[0]);
        op.push(c[0]);
        da.push(data[1]);
        for(i=1; i<k; ++i)
        {
            if(!op.empty())
            {
                ch = op.top();
                if(Pri(c[i], ch))
                {
                    op.push(c[i]);
                    da.push(data[i+1]);
                }
                else
                {
                    y = da.top();
                    da.pop();
                    x = da.top();
                    da.pop();
                    op.pop();
                    z = Cal(x, y, ch);
                    da.push(z);
                    i--;
                }
            }
            else
            {
                op.push(c[i]);
                da.push(data[i+1]);
            }
        }
        z = da.top();
        da.pop();
        while(!op.empty())
        {
            x = da.top();
            da.pop();
            y = z;
            ch = op.top();
            op.pop();
            z = Cal(x, y, ch);
        }
        printf("%0.2lf\n",z);
        //cout<<setioflags(io::fixed)<< setprecision(2)<<z<<endl;
    }
    return 0;
}


这道题目完全自创,没有参考浙大机试指南,发现自己写的代码有一部分比书上好些。是进步。但是还有很多不足!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值