如何找到哪个值最接近C中的数字?

我在C中有以下代码:

#define CONST 1200 int a = 900; int b = 1050; int c = 1400; if (A_CLOSEST_TO_CONST) { // do something } 

检查a,b和c中a是否与CONST最接近的值有什么方便的方法?

编辑:

如果我有3个变量或像这样的数组(它可能超过3个元素)并不重要:

 int values[3] = {900, 1050, 1400}; 

这适用于三个变量:

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

这适用于一个或多个元素的数组,其中n是元素的数量:

 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; } 

看它在线工作: ideone

比较(a-CONST),(b-CONST)和(c-CONST)的绝对值。 无论哪个绝对值最低,哪一个最接近。

这是一种通用方法。 min_element()函数采用int数组,数组大小和指向比较函数的指针。 如果第一个值小于第二个值,则比较谓词返回true 。 刚返回a < b函数将找到数组中的最小元素。 pinouchon()比较谓词执行您的亲密度比较。

 #include  #include  #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; } 

我在Mark Byres代码中添加了一些内容…..

 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]; } 

此函数将采用整数数组并返回最接近CONST的数字。

您需要将常量与每个元素进行比较。 (适用于3个元素但对于更大的元素数量来说这是一个非常糟糕的解决方案,在这种情况下我建议使用某种分而治之的方法)。 比较之后,取其差异,最小差异是const最接近的差异)

这个答案是对您原始问题和评论的编辑的反应。 (请注意,为了确定数组的结尾,我们可以使用不同的方法,我将在这个特定场景中使用的那个是最简单的方法。)

 // I think you need to include math.h for abs() or just implement it yourself. // The code doesn't deal with duplicates. // Haven't tried it so there might be a bug lurking somewhere in it. const int ArraySize = ; const int YourConstant = ; int values[ArraySize] = { ...  ... }; int tempMinimum = abs(YourArray[0] - YourConstant); // The simplest way for (int i = 1; i < ArraySize; i++) { // Begin with iteration i = 1 since you have your 0th difference computed already. if (abs(YourArray[i] - YourConstant) < tempMinumum) { tempMinumum = abs(YourArray[i] - YourConstant); } } // Crude linear approach, not the most efficient. 

对于大型有序集,您应该能够使用二进制搜索来找到两个数字(模数边缘情况)与数字边界,其中一个必须是最接近的。

因此,您将能够实现O(Log n)性能而不是O(n)。

伪代码:

 closest_value := NULL closest_distance := MAX_NUMBER for(value_in_list) distance := abs(value_in_list - CONST) if (distance < closest_distance) closest_value := value_in_list closest_distance := distance print closest_value, closest_distance