gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:55:24 26 4
gpt4 key购买 nike

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

最佳答案

这适用于三个变量:

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

关于c - 如何找到哪个值最接近C中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8233951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com