简体   繁体   English

查找数组中最近的浮点数

[英]Find nearest float in array

How would I get the nearest float in my array to a float of my choice? 如何将数组中最接近的浮点数转换为所选的浮点数? Here is my array: 这是我的数组:

[1.20, 1.50, 1.75, 1.95, 2.10]

For example, if my float was 1.60 , I would like to produce the float 1.50 . 例如,如果我的浮点数是1.60 ,我想生成1.50

Any ideas? 有任何想法吗? Thanks in advance! 提前致谢!

You can do it by sorting the array and finding the nearest one. 您可以通过对数组进行排序并找到最接近的数组来做到这一点。

For this you can use sortDescriptors and then your algorithm will go. 为此,您可以使用sortDescriptors,然后您的算法将运行。

Even you can loop through, by assuming first as the required value and store the minimum absolute ( abs() ) difference, if next difference is lesser than hold that value. 即使您可以遍历,也可以通过将first假定为必需值并存储最小绝对( abs() )差,如果下一个差小于保持该值。

The working sample, however you need to handle other conditions like two similar values or your value is just between two value like 2 lies between 1 and 3. 工作样本,但是您需要处理其他条件,例如两个相似的值,或者您的值介于两个值之间,例如2介于1和3之间。

NSArray *array = @[@1.20, @1.50, @1.75, @1.95, @2.10];

double my = 1.7;
NSNumber *nearest = array[0];

double diff = fabs(my - [array[0] doubleValue]);
for (NSNumber *num in array) {
    double d = [num doubleValue];
    if (diff > fabs(my - d) ) {
        nearest = num;
        diff = my - d;
    }
}

NSLog(@"%@", nearest);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM