问题 A: 简单计算器

作业比赛编号 : 100000602 - 《算法笔记》6.7小节——C++标准模板库(STL)介绍-

>stack的常见用法详解

Codeup新家 (hustoj.com)http://codeup.hustoj.com/contest.php?cid=100000602

书里给的是先转换成后缀表达式再计算的思路,我嫌麻烦就没有做这个处理 

#include<stack>
#include<stdio.h>
#include<cstdlib>
#include<map>
#include<string>
#include<iostream>
using namespace std;

void initMap(map<char, int> &mp)
{
    mp['+'] = 0;
    mp['-'] = 0;
    mp['*'] = 1;
    mp['/'] = 1;
}

void pushSym(char c, stack<char>& sym, stack<double>& numbers, map<char, int>& mp)
{
    char sy;
    double a, b, f;
    while (sym.empty() == false && mp[c] <= mp[sym.top()])
    {
        sy = sym.top();
        sym.pop();
        b = numbers.top();
        numbers.pop();
        a = numbers.top();
        numbers.pop();
        if (sy == '+')f = a + b;
        else if (sy == '-')f = a - b;
        else if (sy == '*')f = a * b;
        else if (sy == '/')f = a / b;
        numbers.push(f);
    }
    sym.push(c);
}

double calcu(stack<double>& numbers, stack<char>& sym)
{
    char sy;
    double a, b, f=numbers.top();
    while (sym.empty() == false)
    {
        sy = sym.top();
        sym.pop();
        b = numbers.top();
        numbers.pop();
        a = numbers.top();
        numbers.pop();
        if (sy == '+')f = a + b;
        else if (sy == '-')f = a - b;
        else if (sy == '*')f = a * b;
        else if (sy == '/')f = a / b;
        numbers.push(f);
    }
    numbers.pop();
    return f;
}

int main()
{
    stack<double> numbers;
    stack<char> sym;
    map<char,int> mp;
    initMap(mp);

    while (1)
    {
        double num;///如果是int就处理不了较大数据,虽然double也可能失真,但是还是AC了
        string str;
        getline(cin, str);
        if (str == "0")break;
        else
        {

            while (str.size()!=0)
            {
                string s;
                if (str.find(' ') != string::npos)
                {
                    s= str.substr(0, str.find(' '));
                    str.erase(0, str.find(' ')+1);
                }
                else
                {
                    s = str;
                    str.clear();
                }
                num = stof(s);string转double
                numbers.push(num);
                if (str.size()==0)break;
                string sy;
                sy = str[0];
                str.erase(0, str.find(' ')+1);
                char c = *(sy.c_str());
                pushSym(c, sym, numbers, mp);
            }
            double result;
            result = calcu(numbers, sym);
            printf("%.2lf\n", result);
            
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值