如何以编程方式检查变量是否接近x?

Dan*_*pez 6 c# floating-point double int limits

是否可以检查变量(变量可以是float,double或int)是否接近某个数字.我做了一些谷歌搜索,但它没有任何结果.

例如,当n ^ x为x变得更负时,它接近零.

Dar*_*rov 2

您可以使用Math.Abs​​ 函数来测量给定值是否接近 x:

double x = ...
double someVariable = ...

// define the precision you are working with
double epsilon = 1e-6;

// now test whether someVariable is approaching x
if (Math.Abs(someVariable - x) < epsilon)
{
    // someVariable is approaching x given the precision you have defined
}
Run Code Online (Sandbox Code Playgroud)