所以我正在做一个自定义的滑块,我很接近得到它,但是似乎不知道如何让它四舍五入到最接近的5。有人能帮我解决这个问题吗?
int distance = progress;
roundedValue = roundf(distance / 5.0f) * 5.0f;
int distanceInt = (int) roundedValue;
return [NSString stringWithFormat:@"%i", distanceInt];提前感谢!
发布于 2013-07-12 01:56:16
我试过这种方式,没有比你更多的了,它给了我你想要的。
-(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]);
}
}输出:
0 -> 0 4 -> 5 8 -> 10 12 -> 10 16 -> 15 20 -> 20 24 -> 25 28 -> 30 32 -> 30 36 -> 35 40 -> 40 44 -> 45 48 -> 50 etc
发布于 2013-11-07 21:34:30
现在,这个老问题顺带而过,CodaFi的话听起来是真的。对于其他路人,请注意:
int distanceInt = (distance / 5) * 5; // largest multiple of 5 <= distance
if ( (distance - distanceInt) >= 3 )
distanceInt += 1; // if remainder >= 3 round up不需要浮点。
https://stackoverflow.com/questions/17599931
复制相似问题