[MOOC程序设计与算法二] 递归二

 1.表达式计算 输入为四则运算表达式,仅由整数、+、-、* 、/ 、(、) 组成,没有空格,要求求其值。假设运算符结果都是整数 。"/"结果也是整数

表达式也是递归的定义:

表达式由项的+ -组成 ,项由因子的* / 组成,  因子可以是整数,也可以由带括号的表达式组成

判断是否还有表达式,项和因子,需要只读不取,根据读出的字符确定是否需要取,并做后面的运算,否则会出错。

cin.peek()只读一个字符而不取  cin.get()读取一个字符

代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;

int factor_value()
{
    int expression_value(void);
    int ret = 0;
    char c = cin.peek();
    if (c == '(') {
        c = cin.get();
        ret = expression_value();
        cin.get();
    }
    else {
        while (isdigit(c)) {
            c = cin.get();
            ret = ret*10 + c -'0';
            c = cin.peek();
        }
    }
    return ret;
}

int term_value()
{
    int ret = factor_value();
    char c = cin.peek();
    while (1) {
        if (c == '*' || c == '/') {
            c = cin.get();
            if (c == '*')
                ret *= factor_value();
            else ret /= factor_value();
            c = cin.peek();
        }
        else break;
    }
    return ret;
}

int expression_value()
{
    int ret = term_value();
    char c = cin.peek();
    while (1) {
        if (c == '+' || c == '-') {
            c = cin.get();
            if (c == '+')
                ret += term_value();
            else
                ret -= term_value();
            c = cin.peek();
        }
        else
            break;
    }
    return ret;
}

int main()
{
    freopen("1.txt", "r", stdin);
    cout << expression_value() << endl;

    return 0;
}

 

转载于:https://www.cnblogs.com/whileskies/p/7301567.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值