有理数计算器
我想做一个有理数计算器,但我不知道如何忽略一些字符。 例如,如果程序必须计算表达式“2/9+9/3”并且答案应该采用非简化形式,那么在输入时如何忽略上述表达式中的“/”?
I want to make a rational number calculator, but I don't know how to neglect some characters. E.g., if the program has to calculate the expression "2/9+9/3" and the answer should be in unsimplified form, how to neglect '/' in the above expression while taking input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要定义一个了解有理数的语法/解析器。 对于您的示例输入,您希望最终得到一个包含如下内容的解析树:
然后您将编写了解有理数计算时使用的各种技巧的代码,以便实现
add
例如,操作可以检查其输入参数的最大公约数,并进行转换可添加的数字。在这种情况下,它可能会将参数重写为
rational(2, 9)
和rational(27, 9)
,然后进行加法,最终得到 <代码>有理(29, 9)。您可以有一个单独的函数来进行简化,可以将其简化回
3+rational(2, 9)
。I think you need to define a syntax/parser that knows about rational numbers. For your sample input you would like to end up with a parse tree holding something like this:
Then you'd write code that knows about the various tricks used when calculating with rationals, so that the code implementing the
add
operation can, for instance, check for the greatest common divisor of its input arguments, and transform the numbers to be addable.In this case, it would probably rewrite the arguments to be
rational(2, 9)
andrational(27, 9)
, then do the addition, thus ending up withrational(29, 9)
.You could have a separate function that does simplification, that can simplify that back down to
3+rational(2, 9)
.