Math c+中的算术表达式输入计算+;
我总是要求用户输入Math c+中的算术表达式输入计算+;,math,expression,Math,Expression,我总是要求用户输入x和y,然后计算结果。这是一个非常简单的例子: intmain() { int x,y; cout您应该实现中缀符号解析算法 例如;我不会花时间重新发明轮子。 我会使用现有的脚本语言进行用户输入,我个人会选择lua,尽管其他很多都是可行的 这大概就是您的应用程序使用lua作为解释器时的样子 #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include <string> #include <
x
和y
,然后计算结果。这是一个非常简单的例子:
intmain()
{
int x,y;
cout您应该实现中缀符号解析算法
例如;我不会花时间重新发明轮子。
我会使用现有的脚本语言进行用户输入,我个人会选择lua,尽管其他很多都是可行的
这大概就是您的应用程序使用lua作为解释器时的样子
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <string>
#include <iostream>
int main()
{
using namespace std;
string x,y;
cout << "Please enter x" <<endl;
cin >> x ;
cout << "please enter y" <<endl;
cin >> y;
//TODO: You may want to check that they've entered an expression
//
lua_State * L = lua_open();
// We only import the maths library, rather than all the available
// libraries, so the user can't do i/o etc.
luaopen_math(L);
luaopen_base(L);
// We next pull the math library into the global namespace, so that
// the user can use sin(x) rather than math.sin(x).
if( luaL_dostring(L,"for k,v in pairs(math) do _G[k] = v end") != 0)
{
std::cout<<"Error :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
// Convert x to an integer
x = "return "+x;
if( luaL_dostring(L,x.c_str()) != 0 )
{
std::cout<<"Error in x :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
int xv = lua_tointeger(L,-1);
lua_pop(L,1);
// Convert y to an integer
y = "return "+y;
if( luaL_dostring(L,y.c_str()) != 0 )
{
std::cout<<"Error in y :"<<lua_tostring(L,-1)<<std::endl;
return 1;
}
int yv = lua_tointeger(L,-1);
lua_pop(L,1);
int result = xv + yv ;
cout << result << endl;
return 0;
}
#包括“lua.h”
#包括“lualib.h”
#包括“lauxlib.h”
#包括
#包括
int main()
{
使用名称空间std;
字符串x,y;
cout根据Michael Anderson的回答,使用我的Lua引擎前端,代码的核心将是
ae_open();
ae_set("x",x);
ae_set("y",y);
int result = ae_eval("x + y");
ae_close();
当然,有趣的是当ae_eval
从用户那里获取包含任意表达式输入的字符串时。不确定如何使用它,我想计算这个表达式:4+5/3
,条件是用户直接输入这个表达式。如果我们使用字符串,我们可以读取操作吗?是的,您可以读取但是中缀符号有点困难。我说,这项工作的调车场算法。你可以研究你大脑的后缀符号。可能的重复和其他几个问题。感谢链接,我在发布这个问题之前查看了它,但它没有帮助,所以我决定发布一个新的问题。在这种情况下,OP会更好ff使用my@lhf很有可能-但我没有ae方面的经验。也许你可以/应该提供一个示例,说明使用ae时代码会是什么样子?