表达式求值

举报
ReCclay 发表于 2022/02/22 01:45:07 2022/02/22
【摘要】 表达式求值(间接递归) 1.表达式是由项通过+ - 组成 2.项是由因子通过* /组成 3.因子可以为一个整数,因子也可以由左右括号和表达式组成(因子的> 单个整数就相当于递归的终止...

表达式求值(间接递归)

1.表达式是由项通过+ - 组成

2.项是由因子通过* /组成

3.因子可以为一个整数,因子也可以由左右括号和表达式组成(因子的> 单个整数就相当于递归的终止条件)

PS:看程序如果有困难的话,建议进入debug中!

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int factor_value();
int term_value();
int expression_value();
int main()
{
    cout << expression_value() << endl;
    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;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76

文章来源: recclay.blog.csdn.net,作者:ReCclay,版权归原作者所有,如需转载,请联系作者。

原文链接:recclay.blog.csdn.net/article/details/60784950

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。