gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:33 25 4
gpt4 key购买 nike

我在 C# 中遇到一个奇怪的问题,我需要计算一些数学字符串表达式,这些表达式可能被 0 整除。这是一个例子:

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

我目前正在使用 NCalc用于评估此表达式的库,如果当前表达式中的 z 参数为 0,则会抛出 DivideByZeroException

我尝试通过以下方式捕获异常:

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

// ...

exp.Evaluate(); // Throws a DivideByZeroException

} catch (DivideByZeroException e) {
//ignored
}

但是,我需要以节省时间的方式对该表达式求值 6000 多次(使用不同的变量),因此每次都捕获异常会显着降低我的应用程序速度。

我有多个这样的表达式,每个表达式都是由用户输入的。我不知道给定的表达式是否试图除以零。

有没有办法以“安全”的方式评估 C# 中的数学表达式,其中尝试除以 0 将返回一个静态数字(0,或无穷大),而不抛出异常?

最佳答案

尝试使您的值成为 float 。

Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. 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. Because the following example uses floating-point division rather than integer division, the operation does not throw a DivideByZeroException exception.

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

关于c# - 如何评估 C# 中可以被零除的字符串表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com