从字符串求解方程,得到C [英] Solve equation from string to result in C

查看:134
本文介绍了从字符串求解方程,得到C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,如果有人有关于如何做的东西听起来很简单,但不想看起来像在尝试编程时的信息或经验。
这个想法是:给出一个包含方程的字符串,例如:2 * x = 10(这很简单,但它可能变得很复杂,比如sqrt(54)* 35 = x ^ 2;等等....),程序将返回x = 5,并可能给出他如何到达那里的日志。

I would like to know if anyone has info or experience on how to do something which sounds simple but doesn't look like it when trying to program it. The idea is : give a string containing an equation, such as : "2*x = 10" for example (this is simple, but it could get very complex, such as sqrt(54)*35=x^2; and so on....) and the program would return x = 5 and possibly give a log of how he got there.

这是可行的吗?如果是这样,有没有人领导?对于信息有这个网站(http://www.numberempire.com/equationsolver.php)在PHP中做同样的事情,但不是开源。

Is this doable ? If so, does anyone have a lead ? For info there is this site (http://www.numberempire.com/equationsolver.php) which does the same thing in PHP, but isn't open source.

推荐答案

这被称为解析,虽然计算机科学已经解决了这个问题,直到你彻底理解它。有一个完整的计算机科学学科,描述如何解决这个问题。在C中,您必须定义输入的语法(可能包含优先规则),然后对输入执行词法分析,然后解析结果,最后评估您的解析树。

This is called "parsing", and although computer science has already solved this problem it isn't simple at all until you understand it thoroughly. There's an entire computer-science discipline that describes how to solve this problem. In C you must define the grammar of your input (possibly with precedence rules in it), then perform lexical analysis on your input, then parse the result and finally evaluate your parse tree.

然而,在像Ruby这样的语言中,因为你对字符串操作有如此全面的支持,并且因为你有如此巨大的运行时间能力,代码行如下:

In languages such as Ruby, however, because you have such thorough support for string manipulation and because you have such tremendous runtime power you can solve your problem with a single line of code like so:

puts(eval($_)) while gets

是的,这将超出您的要求。

Yes, that will cover more than what you ask for.

这篇关于从字符串求解方程,得到C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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