C++ 四舍五入到最接近的数字倍数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29557459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:12:09  来源:igfitidea点击:

Round to nearest multiple of a number

c++math

提问by Luchian Grigore

Is there an idiomatic way to round to the nearestmultiple of a number, short of rounding both up and down and seeing which one is closest?

是否有一种惯用的方法可以舍入到最接近的数字倍数,而不是向上和向下舍入并查看哪个最接近?

Assume only integers:

假设只有整数:

number   multiple   result
12       5          10
13       5          15
149      10         150

回答by Mike Seymour

Add half of the multiple, then round down.

添加倍数的一半,然后向下取整。

result = ((number + multiple/2) / multiple) * multiple;

or

或者

result = number + multiple/2;
result -= result % multiple;

This rounds up if the number is exactly in the middle. You might need to tweak the calculation if you want different behaviour in that case. Also, beware overflow if numbermight be near the top of the type's range.

如果数字正好在中间,则四舍五入。如果您想要在这种情况下不同的行为,您可能需要调整计算。此外,如果number可能接近类型范围的顶部,请注意溢出。

回答by Muhamad Iqbal

I've answered this before on Rounding off a number to the next nearest multiple of 5

我之前在将数字四舍五入到下一个最接近的 5 的倍数上回答了这个问题

With using cmath::abs

随着使用 cmath::abs

int rounded = n + abs((n % denom) - denom);

You can change denomwith any denomination you want

您可以更改denom任何您想要的面额