gpt4 book ai didi

objective-c - 从 objective-c 中的一组 int 值中找到最接近的 Int 值

转载 作者:行者123 更新时间:2023-12-02 22:27:27 24 4
gpt4 key购买 nike

objective 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/

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