用公差计算值

Dr.*_*ail 2 c#

我有一个输入值,例如

decimal input = 100.4m;
Run Code Online (Sandbox Code Playgroud)

和一个比较值/一个可以改变的容差。所以在这个例子中99.5to100.5是有效的,其他输入值不是。

decimal tolerance = 0.5m;
decimal compareValue = 100m;
Run Code Online (Sandbox Code Playgroud)

问题:有没有比这更优雅的验证方式:

bool isValid = (input >= compareValue - tolerance) && (input <= compareValue + tolerance);
Run Code Online (Sandbox Code Playgroud)

Sea*_*ean 6

这取决于你如何定义优雅......!您也可以使用 Abs 进行检查:

bool isValid = Math.Abs(input - compareValue) <= tolerance;
Run Code Online (Sandbox Code Playgroud)