表达式计算,递归的思路,表达式本身的定义就是递归

#include<iostream>
using namespace std;
int factor_value();
int term_value();
int expression_value();
int factor_value()//因子
{
    int result = 0;
    char op = cin.peek();//用op存储缓冲区第一个字符,但并不从键盘缓冲区取走
    if (op == '(')//看是不是括号
    {
        cin.get();//从缓冲区读走'('
        result = expression_value();//计算括号内的表达式
        cin.get();//从缓冲区读走')'
    }
    else
    {
        while (isdigit(op))//判断op是不是数字
        {
            cin.get();//从缓冲区拿走op的值
            result = result * 10 + op - '0';//这个用于将读取到的字符转化成整数
            op = cin.peek();//继续看缓冲区的第一个字符
        }
    }
    return result;
}
int term_value()//项
{
    int result = factor_value();
    bool more = true;//判断还没有其他的项
    while (more)
    {
        char op = cin.peek();//看接下来的第一个字符是不是乘号或者除号
        if (op == '*' || op == '/')
        {
            cin.get();//从键盘缓冲区取出op的字符
            int temp = factor_value();
            if (op == '*')
            {
                result *= temp;
            }
            else if (op == '/')
            {
                result /= temp;
            }
        }
        else
        {
            more = false;
        }
    }
    return result;
}
int expression_value()//表达式
{
    int result = term_value();//获取一项的值
    bool more = true;//判断还没有其他的项
    while (more)
    {
        char op = cin.peek();//看接下来的第一个字符是不是加号或者减号
        if (op == '+' || op == '-')
        {
            cin.get();//从键盘缓冲区取出op的字符
            int temp = term_value();
            if (op == '+')
            {
                result += temp;
            }
            else if (op == '-')
            {
                result -= temp;
            }
        }
        else
        {
            more = false;
        }
    }
    return result;
}
int main()
{
    cout << expression_value() << endl;
    return 0;
}

//函数cin.peek()用于从键盘缓冲区看第一个字符,但并不会取走第一个字符
//函数cin.get()用于从键盘缓冲区读走第一个字符,会取走第一个字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值