如何给一个程序方程式 [英] how to give an equation to a program

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

问题描述

如何计算公式?



例如:



cin>> ;等式;

//等式是y = 5 *(x / 2);



然后:

cin>> x;

// x是6;



然后:

// y = 5 *(6/2)= 15;

cout<< y;

// y是15;



等式需要由用户输入输入。



我正在使用visual studio 2010 c ++控制台应用程序。

How can i give an equation to calculate?

For example:

cin>> equation;
//equation is y = 5*(x/2);

then:
cin>>x;
//x is 6;

then:
// y = 5 * ( 6 / 2 ) = 15;
cout<< y;
//y is 15;

the equation needs to be entered from input by the user.

I''m using visual studio 2010 c++ console application.

推荐答案

有一些算法可以解析和分析方程式由计算机使用。



通常将中缀符号转换为RPN(反向波兰符号)。



Shunting Yard Algo [ ^ ]是其中之一(包括C实现)



一旦完成,那么你只需要检查结果来计算最终值(不要忘记替换变量)。



祝你好运。
There are a few algorithms to parse and analyze equations to be used by a computer.

Usually converting the infix notation to a RPN (reverse polish notation) .

Shunting Yard Algo[^] is one of them (with C implementation included)

Once this is done, then you just have to go over the result to compute the final value (without forgetting to substitute the variables).

good luck.


是的,你的程序可以评估(静态)表达式,例如

Yes, your program can evaluate (static) expressions, e.g.
#inclde <iostream>
using namespace std;
int main()
{
  int x;
  cin >> x;
  cout << (5*x/2) << endl;
}





[更新]

如果你需要评估用户提供的''表达式',那么你基本上有两种选择:

  • (可能是更难的)自己构建一个解析器(实际上是一个求值器)用于数学表达式(你可以在网上找到很多例子)。
  • 嵌入一个脚本语言(例如Lua,参见在Stack Overflow上使用Lua评估数学表达式[ ^ ])在您的应用程序中,然后让用户使用这种语言编写表达式。


  • [Update]
    If you need to evaluate ''expressions provided by the user'', then you have basically two alternatives:

    • (possibly the harder one) build yourself a parser (an evaluator, actually) for mathematical expression (you may find many examples on the web).
    • embed a script language (for example Lua, see "Evaluating Mathematical Expressions using Lua" at Stack Overflow[^] ) in your application, then let the user write the expression using such a language.

    • 将exssion作为字符串。

      检查该字符串中的变量。获取RHS中使用的变量值。

      使用中缀求解算法求解中缀表达式。
      take the expession as string.
      check the variable in that string. get the variable values used in RHS.
      Solve the infix expression using infix solve algorithm.


      这篇关于如何给一个程序方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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