有理数计算器

发布于 2024-07-15 10:00:41 字数 93 浏览 4 评论 0原文

我想做一个有理数计算器,但我不知道如何忽略一些字符。 例如,如果程序必须计算表达式“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2024-07-22 10:00:41

我认为您需要定义一个了解有理数的语法/解析器。 对于您的示例输入,您希望最终得到一个包含如下内容的解析树:

   add(rational(2, 9)
       rational(9, 3))

然后您将编写了解有理数计算时使用的各种技巧的代码,以便实现 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:

   add(rational(2, 9)
       rational(9, 3))

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) and rational(27, 9), then do the addition, thus ending up with rational(29, 9).

You could have a separate function that does simplification, that can simplify that back down to 3+rational(2, 9).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文