0

Is there a way to determine if a number is within a range of two specific numbers, if those numbers are changing? For example:

int num1 = -10;
int num2 = 100;
int num3 = 5;

if(num3 > num 1 && num3 < num2){

}

It would be rather easy to determine whether num3 is in between num1 and num2. However, lets say num1 and num2 change dynamically during the running of the program:

num2 becomes -30

All else remains the same. Now the same algorithm as before would no longer work. Is there an elegant way to check if a number is withing a range using dynamically changing max and min values?

  • 2
    The algorithm will still work if the value of one of your ints changes, unless the greater of the two bounds becomes the smaller of the two (which doesn't seem to be the case from your example). Something else is going on here. – FThompson Feb 07 '14 at 02:56
  • Yeha it was meant to be num2 that becomes lower. I fixed the Post –  Feb 07 '14 at 03:20

2 Answers2

1

You can try the following, i create 2 more variable iMin & iMax, and before checking num3 is in rank, we define max value and min value:

int num1 = -10;
int num2 = 100;
int num3 = 5;

if (num3 > Math.min(num1, num2) && num3 < Math.max(num1, num2)) {

}
FThompson
  • 28,352
  • 13
  • 60
  • 93
Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
  • 1
    The intentions of this code can be made more clear through the use of `Math.min` and `Math.max`. – FThompson Feb 07 '14 at 03:02
  • In any of these cases: num1 = num3 num2 = num3 num1 = num2 = num3 Have a look at this post: [link]http://stackoverflow.com/questions/5029409/how-to-check-if-an-integer-is-within-a-range/21368722#21368722 – Luis Rosety Oct 04 '15 at 18:30
0

That's kinda silly. If you have an algorithm in a function and you say you want num3 to be between num1 and num2, that's it. That rule shouldn't change, because num1 or num2 changed. The implementation should be generic and independent of the values.

If you need some verification prior to that, do it. I don't a see any other elegant way to do it.

Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28