C语言中如何找到最接近某个数的值?

发布于 2024-12-17 10:08:11 字数 333 浏览 4 评论 0原文

我在 C 中有以下代码:

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

if (A_CLOSEST_TO_CONST) {
  // do something
}

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

编辑:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

顾冷 2024-12-24 10:08:11

这适用于三个变量:

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

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

陈年往事 2024-12-24 10:08:11

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

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

↙温凉少女 2024-12-24 10:08:11

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

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

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;
}
伴我老 2024-12-24 10:08:11

我正在 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 的数字。

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.

丿*梦醉红颜 2024-12-24 10:08:11

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

You need to compare your constant to every element. (works well for 3 elements but it's a very bad solution for bigger elementcount, in which case i suggest using some sort of divide and conquer method). After you compare it, take their differences, the lowest difference is the one that the const is closest to)

伤感在游骋 2024-12-24 10:08:11

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

// 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 = <your array size>;
const int YourConstant = <your constant>;
int values[ArraySize] = { ... <your numbers> ... };
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.

This answer is a reaction to your edit of the original question and your comment.
(Notice that to determine the end of array we could use different approaches, the one i shall use in this particular scenario is the simplest one.)

// 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 = <your array size>;
const int YourConstant = <your constant>;
int values[ArraySize] = { ... <your numbers> ... };
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.
允世 2024-12-24 10:08:11

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

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

For a large sorted set, you should be able to use a binary search to find the two numbers which (modulo edge cases) border the number, one of those has to be the closest.

So you would be able to achieve O(Log n) performance instead of O(n).

想你的星星会说话 2024-12-24 10:08:11

伪代码:

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        

pseudocode:

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        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文