3 回答
TA贡献1744条经验 获得超4个赞
这适用于正数,不确定负数。它只使用整数数学。
int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = numToRound % multiple;
if (remainder == 0)
return numToRound;
return numToRound + multiple - remainder;
}
编辑:这是一个使用负数的版本,如果用“向上”表示结果总是> =输入。
int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;
int remainder = abs(numToRound) % multiple;
if (remainder == 0)
return numToRound;
if (numToRound < 0)
return -(abs(numToRound) - remainder);
else
return numToRound + multiple - remainder;
}
TA贡献1803条经验 获得超6个赞
没有条件:
int roundUp(int numToRound, int multiple)
{
assert(multiple);
return ((numToRound + multiple - 1) / multiple) * multiple;
}
对于负数,这类似于从零开始舍入
编辑:适用于负数的版本
int roundUp(int numToRound, int multiple)
{
assert(multiple);
int isPositive = (int)(numToRound >= 0);
return ((numToRound + isPositive * (multiple - 1)) / multiple) * multiple;
}
如果multiple是2的幂
int roundUp(int numToRound, int multiple)
{
assert(multiple && ((multiple & (multiple - 1)) == 0));
return (numToRound + multiple - 1) & -multiple;
}
TA贡献2039条经验 获得超7个赞
当因子始终为正时,这种方法有效:
int round_up(int num, int factor)
{
return num + factor - 1 - (num - 1) % factor;
}
编辑:返回round_up(0,100)=100。请参阅下面的保罗评论,以获得返回的解决方案round_up(0,100)=0。
添加回答
举报