C语言中如何找到最接近某个数的值?
我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这适用于三个变量:
这适用于一个或多个元素的数组,其中 n 是元素数量:
在线查看它的工作情况: ideone
This works for three variables:
This works with an array of one or more elements, where n is the number of elements:
See it working online: ideone
比较 (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.
这是一个通用的方法。
min_element()
函数接受一个 int 数组、数组大小和指向比较函数的指针。如果第一个值小于第二个值,则比较谓词返回true。刚刚返回a < 的函数b
将找到数组中的最小元素。pinouchon()
比较谓词执行您的紧密度比较。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 returneda < b
would find the smallest element in the array. Thepinouchon()
comparison predicate performs your closeness comparison.我正在 Mark Byres 代码中添加一些内容......
该函数将采用整数数组并返回最接近 CONST 的数字。
I m adding something in Mark Byres code.....
This function will take an array of integers and return the number which is closest to the CONST.
您需要将常数与每个元素进行比较。 (对于 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)
此答案是对您对原始问题和评论的编辑的反应。
(请注意,为了确定数组的末尾,我们可以使用不同的方法,我在这一特定场景中使用的方法是最简单的方法。)
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.)
对于大型排序集,您应该能够使用二分搜索来查找与数字相邻的两个数字(模边缘情况),其中一个必须是最接近的。
因此,您将能够实现 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).
伪代码:
pseudocode: