题解 | #计算表达式#

计算表达式

http://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

while True:
    try:
        s = input()
        print(int(eval(s)))
    except:
        break

#include<bits/stdc++.h>
using namespace std;

int Priority(char c)    //定义优先级顺序 #, $, +-, */
{
    if(c == '#')
        return 0;
    else if(c == '$')
        return 1;
    else if(c == '+' || c == '-')
        return 2;
    else if(c == '*' || c == '/')
        return 3;
    return 0;
}

double getNumber(string str, int& index)
{
    double number = 0;
    while (isdigit(str[index]))
    {
        number = number * 10 + str[index] - '0';
        index++;
    }
    return number;
}

double Calculate(double x, double y, char op)
{
    double result = 0;
    if(op == '+'){
        result = x + y;
    }
    if(op == '-'){
        result = x - y;
    }
    if(op == '*'){
        result = x * y;
    }
    if(op == '/'){
        result = x / y;
    }
    return result;
}

int main()
{
    string str;
    while (getline(cin, str))
    {
        if(str == "0")
            break;
        stack<char> operation;
        stack<double> number;
        str += '$';
        operation.push('#');
        int index = 0;
        while (index < str.size())
        {
            if (str[index] == ' ')
                index++;
            else if(isdigit(str[index]))
                number.push(getNumber(str, index));
            else
            {
                if(Priority(operation.top()) < Priority(str[index]))
                {
                    operation.push(str[index]);
                    index++;
                }
                else
                {
                    double y = number.top();
                    number.pop();
                    double x = number.top();
                    number.pop();
                    number.push(Calculate(x, y, operation.top()));
                    operation.pop();
                }
            }
        }
        printf("%.lf\n", number.top());
    }
    return 0;
}
全部评论

相关推荐

24分钟1.自我介绍2.黑盒测试用例设计方法3.运用刚才的测试方法对手机端淘宝购物车结算页面进行测试4.测试流程5.需求文档没有标明边界值,怎么确定边界值,确定边界值后怎么测6.你们公司自动化测试是测业务主流程还是新需求反问:不足之处答:问答问题前思考3s再答,针对提问再答
一笑而过2222:边:边界值分析法(处理输入边界) 类:等价类划分法(划分有效 / 无效输入) 定:判定表法(多条件组合的逻辑判定) 因:因果图法(分析输入输出的因果关系) 迁:状态迁移法(覆盖系统状态转换路径) 场:场景法(模拟端到端业务流程) 正:正交试验法(多因素组合的测试优化) 错:错误推测法(基于经验推测潜在漏洞) 记忆逻辑链(按测试场景优先级排序) 先处理明确输入:边界值 + 等价类(边类) 再处理条件组合:判定表 + 因果图(定因) 接着处理状态与流程:状态迁移 + 场景法(迁场) 最后优化多因素与补漏:正交试验 + 错误推测(正错)
查看6道真题和解析
点赞 评论 收藏
分享
05-25 10:45
门头沟学院 Java
Frank_zhang:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务