验证数学方程式c ++ [英] Verify Mathematical Equation c++

查看:98
本文介绍了验证数学方程式c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试构建一个非常简单的编译器.我创建了一个函数,可以使用调车码算法将中缀表示法的数学方程式转换为RPN,但是我遇到了问题.我没有在转换函数中包含错误检查功能,因此我想知道是否有一种简单的方法来检查中缀表示法中的函数是否使用正确的中缀表示法语法.这样一来,我就可以保留当前的转换功能,而不会被错误检查所掩盖.

解决方案

如果表达式仅由括号,值(常量和/或标识符)以及前缀,后缀和中缀运算符组成,则需要两个错误条件检查:

  1. 括号必须匹配.很难用分流码算法注意到这一点,因为在算法中有一个点,当输入中遇到一个封闭的括号时,一个开放的括号会从堆栈中弹出.如果您过度叠加堆栈,或者在输入结束时没有弹出整个堆栈,则括号不平衡.

  2. 令牌必须符合以下简单的正则表达式:

    PRE* VAL POST* ( INFIX PRE* VAL POST* )*
    

    其中

    • PRE是前缀运算符或(
    • POST是后缀运算符或)
    • VAL是一个值:常数或标识符

这实际上简化为两种状态的机器:初始状态(状态0)可以称为期望值",而另一种状态(状态1)可以称为期望运算符".仅状态1正在接受,并且转换如下:

State 0:
    PRE   → State 0
    VAL   → State 1

State 1:
    POST  → State 1
    INFIX → State 0

所有其他转换都将变为错误.

通常需要实现此状态机,以正确处理一元减号(以及其他可能为前缀或中缀的运算符),无论如何,将其集成到您的输入处理中非常简单.

I am currently trying to build a very simple compiler. I have created a function that converts a mathematical equation in infix notation to RPN using the shunting-yard algorithm however I have encountered a problem. I did not include error checking in my conversion function so I was wondering if there was a simple way to check if a function in infix notation is in correct infix notation syntax. This would enable me to keep my current conversion function without obscuring it with error checking.

解决方案

If your expressions only consist of parentheses, values (constants and/or identifiers), and prefix, postfix and infix operators, then there are two error conditions you need to check:

  1. The parentheses must match. It's hard not to notice this with the shunting yard algorithm, because there is a point in the algorithm where an open parenthesis is popped off the stack when a close parenthesis is encountered in the input. If you overpop the stack or you don't pop the entire stack at end of input, then the parentheses didn't balance.

  2. The tokens must conform to the following simple regular expression:

    PRE* VAL POST* ( INFIX PRE* VAL POST* )*
    

    where

    • PRE is a prefix operator or an (
    • POST is a postfix operator or a )
    • VAL is a value: a constant or an identifier

That actually reduces to a two-state state machine: the initial state (state 0) could be called "expecting value" and the other state (state 1) could be called "expecting operator". Only state 1 is accepting, and the transitions are as follows:

State 0:
    PRE   → State 0
    VAL   → State 1

State 1:
    POST  → State 1
    INFIX → State 0

All other transitions are to an error.

It's often necessary to implement this state machine in order to properly deal with unary minus (and other operators which could be prefix or infix), and it is, in any event, very simple to integrate into your input handling.

这篇关于验证数学方程式c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆