Ibad Baig
Ibad Baig

Reputation: 2294

Get all middle values between 2 numbers

I want to get a middle value from 2 numbers, lets say the first number I have is >3 and the second number I have is <3 so 3 is a middle value here, and for instance I say first number is >5 and a second number is <3 so 3,4 & 5 should be the result. What is the suitable method for finding these values?

Upvotes: 0

Views: 14440

Answers (3)

FalcoGer
FalcoGer

Reputation: 2467

When using C or C++ you have to be careful because signed integer overflow is undefined. Starting with c++20 you can use std::midpoint to avoid all kinds of pitfalls.

Upvotes: 0

bjedrzejewski
bjedrzejewski

Reputation: 2436

You can add both values and then divide them by 2. If you don't get an integer you can round up or down. If you give a language, you can get a snippet, but here is Java anyway:

int a = 2;
int b = 4;
int middleValue = Math.round((a+b)/2);

EDIT After more details are added, the Java solution would look like this:

int start = 2;
int end = 6;
List<Integer> middleValues= new ArrayList<Integer>();

for(int i =start+1; i <= end; i++){
     middleValues.add(i);
}

Then your middleValues contain what you need.

If you are not dealing with integers, you can also use: Math.floor(start) and Math.ceil(end) in your loop conditions.

Upvotes: 5

jandresrodriguez
jandresrodriguez

Reputation: 794

To find the best middle value ( Average ) you can follow the next formula:

(x + y) / 2

in your example

(3 + 3) / 2

Upvotes: 5

Related Questions