如何将字符串操作转换为数学运算? [英] How to convert a string operation to a math operation?

查看:157
本文介绍了如何将字符串操作转换为数学运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,


我正在制作一个程序,您可以在其中输入数学等式,当您点击输入时,它将显示结果。不幸的是,文本框只能返回一个字符串,而不是一个int,所以我无法弄清楚如何将字符串操作转换为int操作。


以下是我的问题的一个例子:

 string operationA =" 1 + 5  -  2" ;; 
int operationB;

我想以整数格式进行操作B操作A,但我只知道如何转换数字和字符串我不知道如何转换运算符。 / p>

有什么建议吗?

解决方案

这比你想象的要困难得多。不幸的是,C#不包含诸如" eval "之类的运算符。您在javascript中找到用于评估表达式的内容。因此,您需要调用一些外部代码来进行评估,
或调用CSharpCompiler来编译表达式,然后调用已编译的代码,或者编写自己的解析器和解释器来计算表达式的结果。前段时间我写了一篇文章解释了如何做后者;不幸的是
这篇文章是用西班牙语写的,所以它对你来说可能不是很有用,但你至少可以查看代码来看看它是如何工作的:


< a href ="https://www.scribd.com/document/23194492/Como-crear-un-interprete-de-expresiones-en-NET"> https://www.scribd.com/document/23194492/Como -crear-un-interprete-de-expresiones-en-NET


代码功能齐全,因此如果您复制并粘贴它,您将能够评估您的操作通过这样做:


Intérpreteinitp=newIntérprete(operationA); operationB =(int)intrp.Evaluar(0);





Hey guys,

I am making a program where you enter a math equation and when you click enter it will show the result. Unfortunately, the textbox can only return a string, not an int so I can't figure out how to turn a string operation to an int operation.

Heres an example of my problem:

string operationA = "1 + 5 - 2";
int operationB;

I want to make operation B Operation A in integer format but I only know how to convert numbers and strings I don't know how to convert operators.

Any suggestions guys?

解决方案

It is MUCH more difficult than you think. Unfortunately, C# does not contain an operator such as the "eval" that you find in javascript for evaluating an expression. So you need to either invoke some external code to do the evaluation, or invoke the CSharpCompiler to compile the expression and then invoke the compiled code, or write your own parser and interpreter to calculate the result of the expression. I wrote an article some time ago that explains how to do the latter; unfortunately the article is written in Spanish, so it will probably not be very useful to you, but you can at least look at the code to see how it works:

https://www.scribd.com/document/23194492/Como-crear-un-interprete-de-expresiones-en-NET

The code is fully functional, so if you copy and paste it you will be able to evaluate your operation by doing this:

Intérprete intrp = new Intérprete(operationA); operationB = (int)intrp.Evaluar(0);


这篇关于如何将字符串操作转换为数学运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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