二、实现算数加减

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int factor_value();
int term_value();
int expression_value();
int main(){
    cout<<expression_value();
    return 0;
}
int expression_value(){
    int result = term_value();
    bool more = true;
    while(more){
        char op = cin.peek();
        if(op=='+'||op=='-'){
            cin.get();
            int value = term_value();
            if(op=='+') result += value;
            else result -=value;
        } else more=false;
    }
    return result;
}
int term_value(){
    int result = factor_value();
    while(true){
        char op = cin.peek();
        if(op=='*'||op=='/'){
            cin.get();
            int value = factor_value();
            if(op=='*')
                result *= value;
            else result /=value;
        } else break;
    }
    return result;
}
int factor_value(){
    int result = 0;
    char c = cin.peek();
    if(c=='('){
        cin.get();
        result = expression_value();
        cin.get();
    } else{
        while(isdigit(c)){
            result = 10*result+c-'0';
            cin.get();
            c= cin.peek();
        }
    }
    return  result;
}

编译环境g++4.9

运行测试如下:

 

posted @ 2019-06-10 17:40  秃桔子  阅读(214)  评论(0编辑  收藏  举报

如果您有编程方面或者学术方面的需求请在微信公众号搜索

桔子科研


或者识别下方二维码,第一时间获取编程有趣的知识和最新科研学术成果。