好的 - 我几乎不好意思在这里发帖(如果有人投票关闭,我会删除),因为这似乎是一个基本问题.
OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.
这是在 C++ 中四舍五入到一个数字的倍数的正确方法吗?
Is this the correct way to round up to a multiple of a number in C++?
我知道还有其他与此相关的问题,但我特别想知道在 C++ 中执行此操作的最佳方法是什么:
I know there are other questions related to this but I am specficially interested to know what is the best way to do this in C++:
int roundUp(int numToRound, int multiple) { if(multiple == 0) { return numToRound; } int roundDown = ( (int) (numToRound) / multiple) * multiple; int roundUp = roundDown + multiple; int roundCalc = roundUp; return (roundCalc); }更新:抱歉,我可能没有表达清楚.以下是一些示例:
Update: Sorry I probably didn't make intention clear. Here are some examples:
roundUp(7, 100) //return 100 roundUp(117, 100) //return 200 roundUp(477, 100) //return 500 roundUp(1077, 100) //return 1100 roundUp(52, 20) //return 60 roundUp(74, 30) //return 90 推荐答案这适用于正数,不确定负数.它只使用整数数学.
This works for positive numbers, not sure about negative. It only uses integer math.
int roundUp(int numToRound, int multiple) { if (multiple == 0) return numToRound; int remainder = numToRound % multiple; if (remainder == 0) return numToRound; return numToRound + multiple - remainder; }这是一个适用于负数的版本,如果向上"表示结果总是 >= 输入.
Here's a version that works with negative numbers, if by "up" you mean a result that's always >= the input.
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; }更多推荐
四舍五入到最接近的数字倍数
发布评论