C# 检查变量值是否彼此接近

C# 检查变量值是否彼此接近,c#,math,C#,Math,假设我们有两个变量: int test = 50; int test1 = 45; 现在我想检查test1是否在-5/+5(包括-5/+5)范围内接近测试。我怎么做?试试: if (Math.Abs(test - test1) <= 5) { // Yay!! } 这将调用数学绝对函数,该函数返回正值,即使为负值。Math.Abs-5=5听起来好像你只是想测试这两个数字之间的差值是否在某个范围内 using System; ... if (Math.Abs(test - tes

假设我们有两个变量:

int test = 50;
int test1 = 45;
现在我想检查test1是否在-5/+5(包括-5/+5)范围内接近测试。我怎么做?

试试:

if (Math.Abs(test - test1) <= 5)
{
    // Yay!!
}

这将调用数学绝对函数,该函数返回正值,即使为负值。Math.Abs-5=5听起来好像你只是想测试这两个数字之间的差值是否在某个范围内

using System;
...
if (Math.Abs(test - test1) <= 5) return true;
// Get the difference
int d = test - test1;

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

您可能希望将其封装在函数中。 不幸的是,您不能使用泛型类型,因为+运算符不支持泛型类型。 因此,需要为int和任何其他类型实现它

public static bool DoesDifferenceExceed(int value, int differentValue, int maximumAllowedDiffernece)
{
    var actualDifference = Math.Abs(value - differentValue);
    return actualDifference <= maximumAllowedDiffernece;
}
public static bool DoesDifferenceExceed(int value, int differentValue, int maximumAllowedDiffernece)
{
    var actualDifference = Math.Abs(value - differentValue);
    return actualDifference <= maximumAllowedDiffernece;
}