Results 1 to 4 of 4

Thread: [RESOLVED] Closest number (C++)

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    Resolved [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.

  2. #2
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Closest number (C++)

    you could find the absolute of the difference.

  3. #3
    Only Slightly Obsessive jemidiah's Avatar
    Join Date
    Apr 2002
    Posts
    2,431

    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.
    The time you enjoy wasting is not wasted time.
    Bertrand Russell

    <- Remember to rate posts you find helpful.

  4. #4
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width