确定 - 我都不好意思在这里张贴这一点(我会删除,如果有人票关闭),因为它似乎是一个基本的问题
。这是围捕到一些在C ++中多了正确的方法是什么?
我知道有与此相关的其他问题,但我specficially兴趣知道什么是做这在C ++的最好方式:
INT综合报告(INT numToRound,诠释多) { 如果(多个== 0) { 返回numToRound; } INT ROUNDDOWN =((INT)(numToRound)/多)*倍数; INT综述= ROUNDDOWN +多; INT roundCalc =整; 返回(roundCalc); }
更新: 对不起,我可能没做意图明显。下面是一些例子:
综合报告(7,100) //返回100 综合报告(117,100) //返回200 综合报告(477,100) //返回500 综合报告(1077,100) //返回1100 综合报告(52,20) //返回60 综合报告(74,30) //返回90
编辑:感谢所有的答复。以下是我去了:
INT综合报告(INT numToRound,诠释多) { 如果(多个== 0) { 返回numToRound; } INT余数= numToRound%多; 如果(余== 0) { 返回numToRound; } 返回numToRound +多 - 其余部分; }解决方案
这适用于正数,不知道负面的。它仅使用整数运算。
INT综合报告(INT numToRound,诠释多) { 如果(多个== 0) 返回numToRound; INT余数= numToRound%多; 如果(余== 0) 返回numToRound; 返回numToRound +多 - 其余部分; }
编辑:这是一个与负数的作品,版本,如果按向上你的意思是一个结果总是> =输入
。 INT综合报告(INT numToRound,诠释多) { 如果(多个== 0) 返回numToRound; INT余数= ABS(numToRound)%多; 如果(余== 0) 返回numToRound; 如果(numToRound℃,) 返回 - (ABS(numToRound) - 余数); 其他 返回numToRound +多 - 其余部分; }OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.
Is this the correct way to round up to a multiple of a number in 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 90EDIT: Thanks for all the replies. Here is what I went for:
int roundUp(int numToRound, int multiple) { if(multiple == 0) { return numToRound; } int remainder = numToRound % multiple; if (remainder == 0) { return numToRound; } return numToRound + multiple - remainder; }解决方案
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; }Edit: 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; }
更多推荐
C ++:舍入到数字的最接近的倍数
发布评论