侧边栏
首页代码

简单计算器

题目大意

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

sample input

1 + 2
4 + 2 * 5 - 7 / 11
0

sample output

3.00
13.36

思路

读入第一个数字以后 循环输入 “运算符 数字字符” 如果运算符是+则数字入栈,-则-数字入栈,乘则将栈顶与数字相乘 入栈,÷跟乘操作一样。
当字符不为空格时,就结束了。
注意输入第一个数字的后面跟一个字符 判断该字符是否为空格即可知道是不是结束0 注意0+1特例

代码

#include<iostream>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
    double x;
    char spe;
    stack<double>a;//1 + 2 * 2 - 1
    while(scanf("%lf%c",&x,&spe) == 2 && spe == ' ')
    {
        a.push((double)x);
        //printf("%f\n",a.top());
        double num;
        char op,space;
        while(scanf("%c %lf%c",&op,&num,&space) == 3)
        {
            //printf("%.2f\n",num);
            if(op=='+')
                a.push(0.0+num);
            else if(op=='*')
            {
                double t = a.top();
                a.pop();
                a.push(0.0+t * num);
            }
            else if(op=='/')
            {
                double t = a.top();
                a.pop();
                a.push(0.0+t/num);
            }
            else if(op=='-')
            {
                a.push(0.0-num);
            }
            if(space != ' ')
                break;
        }
        double sum = 0.0;
        while(!a.empty())
        {
            //printf("%.2f\n",a.top());
            sum+=a.top();
            a.pop();
        }
        printf("%.2f\n",sum);
    }
}
posted @ 2021-04-21 17:42  AlexStraightUp  阅读(65)  评论(0)    收藏  举报
页脚HTML代码