Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which value is closest to a number in C?

I have the following code in C:

#define CONST 1200
int a = 900;
int b = 1050;
int c = 1400;

if (A_CLOSEST_TO_CONST) {
  // do something
}

What is a convenient way to check whether if a is the closest value to CONST among a,b and c ?

Edit:

It doesn't matter if I have 3 variables or an array like this (it could be more than 3 elements):

int values[3] = {900, 1050, 1400};
like image 990
Benjamin Crouzier Avatar asked Nov 22 '11 21:11

Benjamin Crouzier


4 Answers

This works for three variables:

if (abs(a - CONST) <= abs(b - CONST) && abs(a - CONST) <= abs(c - CONST)) {
    // a is the closest
}

This works with an array of one or more elements, where n is the number of elements:

int is_first_closest(int values[], int n) {
    int dist = abs(values[0] - CONST);
    for (int i = 1; i < n; ++i) {
        if (abs(values[i] - CONST) < dist) {
            return 0;
        }
    }
    return 1;
}

See it working online: ideone

like image 69
Mark Byers Avatar answered Nov 11 '22 11:11

Mark Byers


Compare the absolute value of (a-CONST), (b-CONST) and (c-CONST). Whichever absolute value is lowest, that one is closest.

like image 43
Jonathan M Avatar answered Nov 11 '22 11:11

Jonathan M


Here is a generalized method. The min_element() function takes an int array, array size, and pointer to a comparison function. The comparison predicate returns true if the first values is less than the second value. A function that just returned a < b would find the smallest element in the array. The pinouchon() comparison predicate performs your closeness comparison.

#include <stdio.h>
#include <stdlib.h>

#define CONST 1200

int pinouchon(int a, int b)
{
    return abs(a - CONST) < abs(b - CONST);
}

int min_element(const int *arr, int size, int(*pred)(int, int))
{
    int i, found = arr[0];
    for (i = 1; i < size; ++i)
    {
        if (pred(arr[i], found)) found = arr[i];
    }
    return found;
}

int main()
{
    int values[3] = {900, 1050, 1400};
    printf("%d\n", min_element(values, 3, pinouchon));
    return 0;
}
like image 27
Blastfurnace Avatar answered Nov 11 '22 11:11

Blastfurnace


I m adding something in Mark Byres code.....

int is_first_closest(int values[]) {
    int dist = abs(values[0] - CONST),closest;     //calculaing first difference
    int size = sizeof( values )                    //calculating the size of array
    for (int i = 1; i < size; ++i) {
        if (abs(values[i] - CONST) < dist) {       //checking for closest value
             dist=abs(values[i] - CONST);          //saving closest value in dist
             closest=i;                            //saving the position of the closest value
        }
    }
    return values[i];
}

This function will take an array of integers and return the number which is closest to the CONST.

like image 1
Ravi Kumar Avatar answered Nov 11 '22 13:11

Ravi Kumar