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

编程入门 行业动态 更新时间:2024-10-27 16:29:46
本文介绍了四舍五入到最接近的数字倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好的 - 我几乎不好意思在这里发帖(如果有人投票关闭,我会删除),因为这似乎是一个基本问题.

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; }

更多推荐

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

本文发布于:2023-06-08 23:37:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/591034.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:倍数   最接近   四舍五入   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!