客观C数学函数问题
我有一个 x 值,我想将其与集合中的其他值进行比较,然后确定我的 x 值最接近集合中的哪个值。
例如,假设我有整数 5、10、15、20、25。
确定这些数字中哪个最接近 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 ;
}
}
祝你好运
关于objective-c - 从 objective-c 中的一组 int 值中查找最接近的 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754308/