简体   繁体   English

如何评估C#中可以除以零的字符串表达式?

[英]How to evaluate a string expression in C# which can divide by zero?

I am facing an odd problem in C#, where I need to evaluate some mathematical string expressions, which may divide by 0 . 我在C#中面临一个奇怪的问题,我需要评估一些数学字符串表达式,它可以除以0 Here is an example: 这是一个例子:

string expression = GetUserInput(); // Example: "(x + y) / z", where z may equal to 0

I am currently using NCalc library for evaluating this expression, which throws a DivideByZeroException if the z argument in current expression is 0 . 我目前正在使用NCalc库来评估此表达式,如果当前表达式中的z参数为0则会抛出DivideByZeroException

I tried catching the exception by doing: 我尝试通过以下方式捕获异常:

try {
    string formula = GetUserInput();
    Expression exp = new Expression(formula);

    // ...

    exp.Evaluate(); // Throws a DivideByZeroException

} catch (DivideByZeroException e) {
    //ignored
}

However, I need to evaluate this expression more than 6000 times (with different variables) in a time-efficient manner, so catching an exception every time significantly slows down my application. 但是,我需要以节省时间的方式评估此表达式超过6000次(使用不同的变量),因此每次捕获异常会显着减慢我的应用程序。

I have multiple such expressions, each of which is entered by a user. 我有多个这样的表达式,每个表达式都由用户输入。 I can not know if a given expression attempts to divide by zero or not. 我不知道给定的表达式是否试图除以零。

Is there a way to evaluate a mathematical expression in C# in a "safe" way, where attempting to divide by 0 will return a static number ( 0 , or infinity), without throwing an exception? 有没有办法以“安全”的方式在C#中评估数学表达式,其中尝试除以0将返回静态数字( 0或无穷大),而不会抛出异常?

try making your values floating point. 尝试让你的价值浮点。

Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. 尝试将整数或十进制数除以零会引发DivideByZeroException异常。 To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero. 要防止异常,请确保具有整数或十进制值的除法运算中的分母不为零。 Dividing a floating-point value by zero doesn't throw an exception; 将浮点值除以零不会引发异常; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic. 根据IEEE 754算法的规则,它产生正无穷大,负无穷大或不是数字(NaN)。 Because the following example uses floating-point division rather than integer division, the operation does not throw a DivideByZeroException exception. 因为以下示例使用浮点除法而不是整数除法,操作不会抛出DivideByZeroException异常。

https://msdn.microsoft.com/en-us/library/system.dividebyzeroexception.aspx https://msdn.microsoft.com/en-us/library/system.dividebyzeroexception.aspx

Evaluate z. 评估z。 If z is > 0 then do the operation, else move to next evaluation. 如果z> 0则执行操作,否则转到下一个评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM