使用C语言计算中缀表达式的最简单方法是什么? [英] What is easiest way to calculate an infix expression using C language?
问题描述
假设用户以字符串形式输入中缀表达式?什么是使用C语言评估该表达式结果的最简单的方法(我最简单的意思是简称 t)?
Suppose the user inputs an infix expression as a string? What could be the easiest ( By easiest I mean the shortest) way to evaluate the result of that expression using C language?
可能的方法是通过使用堆栈将其转换为后缀.但这是一个相当漫长的过程.有什么方法可以使用诸如 atoi() 或 eval() 之类的功能,从而使工作更轻松?
Probable ways are converting it to a postfix then by using stacks.But its rather a long process. Is there any way of using functions such as atoi() or eval() that could make the job easier?
推荐答案
C没有内置的"eval"功能,但是有提供此功能的库.
C doesn't have an "eval" function built-in, but there are libraries that provide it.
我强烈建议使用 TinyExpr .它是免费的开源C代码,可通过字符串实现数学评估.TinyExpr只是1 C文件,大约500行代码.我认为您不会找到一种更短或更简单的方法来真正完成(而不仅仅是玩具示例).
I would highly recommend using TinyExpr. It's free and open-source C code that implements math evaluation from a string. TinyExpr is only 1 C file, and it's about 500 lines of code. I don't think you'll find a shorter or easier way that is actually complete (and not just a toy example).
这里是使用它的完整示例,应该说明它的简单程度:
Here is a complete example of using it, which should demostrate how easy it is:
#include "tinyexpr.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%f\n", te_interp("5 * 5", 0)); //Prints 25
return 0;
}
如果您想自己构建一个表达式求解器,我建议您查看 TinyExpr源代码作为起点.非常干净而且易于遵循.
If you want to build an expression solver yourself, I would recommend looking at the TinyExpr source-code as a starting point. It's pretty clean and easy to follow.
这篇关于使用C语言计算中缀表达式的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!