检查变量值是否彼此接近

awa*_*awa -2 c# math

假设我们有两个变量:

int test = 50;
int test1 = 45;
Run Code Online (Sandbox Code Playgroud)

现在我想检查是否test1接近test-5/+ 5(含).我该怎么做?

Bob*_*orn 12

const int absoluteDifference = 5;

int test = 50;
int test1 = 45;

if (Math.Abs(test - test1) <= absoluteDifference)
{
    Console.WriteLine("The values are within range.");
}
Run Code Online (Sandbox Code Playgroud)


Bre*_*ill 6

尝试:

if (Math.Abs(test - test1) <= 5)
{
    // Yay!!
}
Run Code Online (Sandbox Code Playgroud)

这将调用数学"绝对"函数,即使为负数也会返回正值.例如.Math.Abs​​(-5)= 5


Dan*_*ker 5

听起来您只是想测试两个数字之间的差异是否在一定范围内。

// Get the difference
int d = test - test1;

// Test the range
if (-5 <= d && d <= 5)
{
    // Within range.
}
else
{
    // Not within range
}
Run Code Online (Sandbox Code Playgroud)