codeup1918 简单计算器

本文介绍了一个算法,用于解析和计算包含+、-、*、/的非负整数表达式,通过使用栈来处理运算符和操作数,实现对表达式的逐个计算,最后输出结果精确到小数点后两位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

输入

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

输出

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

样例输入 Copy

30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0

样例输出 Copy

12178.21
#include <cstdio>
#include <stack>

bool isJC(char ch) {
    return ch == '+' || ch == '-';
}

bool isCC(char ch) {
    return ch == '*' || ch == '/';
}

bool isOp(char ch) {
    return isCC(ch) || isJC(ch);
}

bool isSpace(char ch) {
    return ch == ' ';
}

bool isNum(char ch) {
    return '0' <= ch && ch <= '9';
}

bool isBig(char ch1, char ch2) {
    return isJC(ch1) && isCC(ch2);
}

double evalVal(double num1, double num2, char op) {
    if (op == '+') {
        return num1 + num2;
    } else if (op == '-') {
        return num1 - num2;
    } else if (op == '*') {
        return num1 * num2;
    } else if (op == '/') {
        return num1 / num2;
    }
    return 0;
}

char str[205];
std::stack<double> nums;
std::stack<char> ops;

void func() {
    int idx = 0;

    int tmpNum;
    double tmpNum1, tmpNum2;
    while (str[idx] != '\0') {
        if (isNum(str[idx])) {
            tmpNum = str[idx] - '0';
            idx++;
            while (str[idx] != '\0' && isNum(str[idx])) {
                tmpNum = tmpNum * 10 + str[idx] - '0';
                idx++;
            }
            nums.push(tmpNum);
        } else if (isSpace(str[idx])) {
            idx++;
        } else if (isOp(str[idx])) {
            while (!ops.empty() && !isBig(ops.top(), str[idx])) {
                tmpNum2 = nums.top();
                nums.pop();
                tmpNum1 = nums.top();
                nums.pop();
                nums.push(evalVal(tmpNum1, tmpNum2, ops.top()));
                ops.pop();
            }
            ops.push(str[idx]);
            idx++;
        }
    }

    while (!ops.empty()) {
        tmpNum2 = nums.top();
        nums.pop();
        tmpNum1 = nums.top();
        nums.pop();
        nums.push(evalVal(tmpNum1, tmpNum2, ops.top()));
        ops.pop();
    }

    printf("%.2f\n", nums.top());
}


int main() {
    scanf("%[^\n]", str);
    getchar();
    while (true) {
        if (str[0] == '0' && str[1] == '\0') {
            break;
        }
        func();
        scanf("%[^\n]", str);
        getchar();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值