Objective c 四舍五入至最接近的五

Objective c 四舍五入至最接近的五,objective-c,floating-point,integer,rounding,Objective C,Floating Point,Integer,Rounding,所以我正在做一个自定义的滑块,我很快就能得到它,但似乎不知道如何将它四舍五入到最接近的5。有人能帮我解决这个问题吗 int distance = progress; roundedValue = roundf(distance / 5.0f) * 5.0f; int distanceInt = (int) roundedValue; return [NSString stringWithFormat:@"%i", distanceInt]; 提前谢谢 我试过这种方法,不过是你,它给了我你想要的

所以我正在做一个自定义的滑块,我很快就能得到它,但似乎不知道如何将它四舍五入到最接近的5。有人能帮我解决这个问题吗

int distance = progress;
roundedValue = roundf(distance / 5.0f) * 5.0f;
int distanceInt = (int) roundedValue;
return [NSString stringWithFormat:@"%i", distanceInt];

提前谢谢

我试过这种方法,不过是你,它给了我你想要的

-(NSString *)test:(NSInteger)progress{
    NSInteger distance = progress;
    float roundedValue = roundf(distance / 5.0f) * 5.0f;
    int distanceInt = (int) roundedValue;
    return [NSString stringWithFormat:@"%i", distanceInt];

}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{

    for (NSInteger i=0; i<100; i+=4) {
        NSLog(@"%ld -> %@",i, [self test:i]);
    }

}

这个老问题现在偶然出现,科达菲的话听起来像是真的。对于任何其他过路人,请考虑:

int distanceInt = (distance / 5) * 5; // largest multiple of 5 <= distance
if ( (distance - distanceInt) >= 3 )
   distanceInt += 1; // if remainder >= 3 round up
int-distanceInt=(距离/5)*5;//最大倍数(5=3)
distanceInt+=1;//如果余数>=3,则四舍五入

不需要浮点。

最接近的5表示什么?84->8588->9092->9096->95???正确,这就是我试图做的。你有什么想法吗?唉,期望一个浮点数插入一个int中,给你一致和正确的结果,这不是一个好的算法。谢谢!仔细观察滑块后,刻度非常精细,当用户将手指滑动到滑块上进行更改时,刻度会增加5、10甚至15。问题是它的屏幕太小,很难精确。我将增量改为25,现在在iPhone上更容易击中目标,当用户将手指放在滑块上时。
int distanceInt = (distance / 5) * 5; // largest multiple of 5 <= distance
if ( (distance - distanceInt) >= 3 )
   distanceInt += 1; // if remainder >= 3 round up