[RESOLVED] Closest number (C++)
For some reason I can't figure this out right now.
I want to compare 2 numbers and find which one is closest to a third number and return it.
like
Closest(50,40,90)
40 and 90 would be compared with 50 and it would return 40 because 40 is closer to 50 than 90.
Re: [RESOLVED] Closest number (C++)
A slightly more novel approach might be to ensure that Arg1 <= Arg2, and then handle each of the following:
Avg = (Arg1 + Arg2) / 2
If Avg < Arg3 Then Return Arg2
Else [that is, if Avg >= Arg3] Then Return Arg1
Drawing this procedure out on a number line should prove it fairly conclusively. I'm sure that this degenerates to Max's method at some basic level.
Re: [RESOLVED] Closest number (C++)
I think it's much easier to just calculate the absolute value of their difference, and then compare that to the first argument. (The first argument is the value to compare with, right?)
For example:
Diff1 = Math.Abs(Arg2 - Arg1)
Diff2 = Math.Abs(Arg3 - Arg1)
If Diff1 > Diff2 Then
'Arg2 > Arg3
ElseIf Diff1 = Diff2 Then
'Arg2 = Arg3
Else 'if Diff1 < Diff2
'Arg2 < Arg3
End if