Round to nearest multiple of a number

后端 未结 2 1379
逝去的感伤
逝去的感伤 2020-12-16 14:26

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

Assume o

2条回答
  •  我在风中等你
    2020-12-16 14:33

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

    With using cmath::abs

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

    You can change denom with any denomination you want

提交回复
热议问题