繁体   English   中英

objective-c舍入数到最近的50

[英]objective-c round number to nearest 50

如何将数字舍入到最接近的X值(例如50)

即47将是50

24将是0

74将是50

99将是100

等等...

我真的不知道从哪里开始研究如何做到这一点......

PS我在iPhone上使用cocoa-touch

非常感谢马克

做这个:

50.0 * floor((Number/50.0)+0.5)

除以50,舍入到最接近的整数,然后乘以50。

所以,结合这里所说的,这里是一般功能:

float RoundTo(float number, float to)
{
    if (number >= 0) {
        return to * floorf(number / to + 0.5f);
    }
    else {
        return to * ceilf(number / to - 0.5f);
    }
}

如果数字为正数:50 *楼层(数字/ 50 + 0.5);

如果数字为负数:50 * ceil(数字/ 50 - 0.5);

我想提出一个不那么优雅但更精确的解决方案; 它仅适用于目标数字。

此示例将给定的秒数舍入到下一个完整的60:

int roundSeconds(int inDuration) {

    const int k_TargetValue = 60;
    const int k_HalfTargetValue = k_TargetValue / 2;

    int l_Seconds = round(inDuration);                           // [MININT .. MAXINT]
    int l_RemainingSeconds = l_Seconds % k_TargetValue;          // [-0:59 .. +0:59]
    if (ABS(l_RemainingSeconds) < k_HalfTargetValue) {           // [-0:29 .. +0:29]
        l_Seconds -= l_RemainingSeconds;                         // --> round down
    } else if (l_RemainingSeconds < 0) {                         // [-0:59 .. -0:30]
        l_Seconds -= (k_TargetValue - ABS(l_RemainingSeconds));  // --> round down
    } else {                                                     // [+0:30 .. +0:59]
        l_Seconds += (k_TargetValue - l_RemainingSeconds);       // --> round up
    }

    return l_Seconds;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM