首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >舍入到最接近的5

舍入到最接近的5
EN

Stack Overflow用户
提问于 2013-07-12 01:37:55
回答 2查看 363关注 0票数 0

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

代码语言:javascript
复制
int distance = progress;
roundedValue = roundf(distance / 5.0f) * 5.0f;
int distanceInt = (int) roundedValue;
return [NSString stringWithFormat:@"%i", distanceInt];

提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-12 01:56:16

我试过这种方式,没有比你更多的了,它给了我你想要的。

代码语言:javascript
复制
-(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

票数 1
EN

Stack Overflow用户

发布于 2013-11-07 21:34:30

现在,这个老问题顺带而过,CodaFi的话听起来是真的。对于其他路人,请注意:

代码语言:javascript
复制
int distanceInt = (distance / 5) * 5; // largest multiple of 5 <= distance
if ( (distance - distanceInt) >= 3 )
   distanceInt += 1; // if remainder >= 3 round up

不需要浮点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17599931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档