我想计算用户在文本框中输入的数学表达式。到目前为止我已经这样做了
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
当我运行这个程序时,它给出了一个错误“Input string was not in a correct format.”
并突出显示 a=double.Parse(finalStringI);
我使用了一个预定义的表达式 a=i*math.log10(i)-1.2 并且它有效,但是当我在文本框中输入相同的内容时它不起作用。 我进行了一些搜索,发现了一些与在运行时编译代码有关的内容。
任何想法如何做到这一点? 我是一个绝对的初学者。 谢谢:)
最佳答案
问题出在您的 stringEvaluate
StringBuilder 中。当您将“sin”替换为“math.sin”时,stringEvaluate
中的内容仍然是一个字符串。你的想法是正确的,但你得到的错误是因为这个事实。
Math.sin
是 Math
类中的一个方法,因此不能像在 a = double.Parse(finalStringI) 中那样对其进行操作;
调用。
实现您的目标将是一项艰巨的任务,但我会这样做:
- 创建一个类(也许称之为 Expression)。
- Expression 类的成员可以包括运算符和操作数的列表,也许还有一个名为
solution
的 double。 - 在实例化时将字符串传递给此类,并使用
StringBuilder
类将其拆分。例如,如果遇到“sin”,请将Math.sin
添加到运算符集合(我将使用其中的对象类型)。 - 所述字符串中的每个运算符和操作数都应放在两个集合中。
- 创建一个方法来相应地评估运算符和操作数集合中的元素。对于超过 2 个运算符的复杂计算,这可能会变得棘手,因为您必须实现 PEMDAS 式算法来重新排序集合以服从操作顺序(从而获得正确的解决方案)。
希望这有帮助:)
关于c# - 求解数学表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656837/