awa
awa

Reputation: 119

Check if variable values are close to each other

Assume we've got two variables:

int test = 50;
int test1 = 45;

Now I want to check if test1 is near of test within -5/+5 inclusive. How can I do it?

Upvotes: 0

Views: 7388

Answers (5)

Philipp M
Philipp M

Reputation: 1891

You may want to capsulate this in a function.
Unfortunately, you can't use a generic type, because this is not supported for the + operator.
So it needs to be implemented for int and any others types specifically.

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

Upvotes: 0

Bob Horn
Bob Horn

Reputation: 34335

const int absoluteDifference = 5;

int test = 50;
int test1 = 45;

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

Upvotes: 15

Daniel A.A. Pelsmaeker
Daniel A.A. Pelsmaeker

Reputation: 50376

Sounds like you simply want to test whether the difference between the two numbers is within a certain range.

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

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

Upvotes: 6

La-comadreja
La-comadreja

Reputation: 5755

using System;
...
if (Math.Abs(test - test1) <= 5) return true;

Upvotes: 2

Brendan Hill
Brendan Hill

Reputation: 3752

Try:

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

This invokes the mathematical "Absolute" function which returns a positive value even if negative. Eg. Math.Abs(-5) = 5

Upvotes: 7

Related Questions