从目标c中的一组int值中找到最接近的Int值 [英] finding the closest Int value from a set of int values in objective c

查看:108
本文介绍了从目标c中的一组int值中找到最接近的Int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标c数学函数问题

我有一个ax值,我想与一组中的其他值进行比较,然后确定集合中的哪个值我的x值最接近。

I've got a x value that i'd like to compare to other values within a set, then determine which value from the set my x value is closest to.

例如,假设我已经获得了5,10,15,20,25的投注。

For example, lets say i've got the ints 5, 10, 15, 20, 25.

确定哪些数字最接近7的最佳方法是什么?

What is the best way to determine which of these numbers is closest to 7?

推荐答案

    int closestDistance = INT32_MAX;
    int indexOfClosestDistance = -1;
    int x = 7;

    for (int i=0; i < [yourArray count]; i++)
    {
        int num = yourArray[i];
        int diff = abs(num - x);

        if (diff < closestDistance)
        {
            closestDistance = diff;
            indexOfClosestDistance = i ;
        }
    }

祝你好运

这篇关于从目标c中的一组int值中找到最接近的Int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆