数字的小数部分问题
什么是一个好的算法来确定添加/减去数字所需的必要分数,以便将其四舍五入到最接近的整数而不使用内置的上限或下限函数?
编辑:寻找数学数字技巧来找出将数字四舍五入到最接近的整数所需的部分。 数学运算越原始越好。 请避免使用其他程序。 无论哪种方法都可以采用 0.5,只要适合您的方法即可。 这不是我的家庭作业问题,我也不打算在任何地方使用它。
What is a good algorithm to determine the necessary fraction needed to add/sub to the number in order to round it to the nearest integer without using the inbuilt ceiling or floor funcitons?
Edit: Looking for a mathematical number trick to figure out the part needed to round the number to the nearest integer. The more primitive the math operations the better. Please avoid using other's procedures. 0.5 can be taken eitherway, whatever suits your method. This is NOT my homework question, nor am I going to use this anywhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将数字除以 1 以获得小数部分,如果大于 0.5,则向上舍入,否则向下舍入;
或者
将数字除以 0.5,如果为奇数,则向上舍入,否则向下舍入
Mod the number with one to get the decimal part, if its >0.5, round up, else round down
OR
Divide the number by 0.5, if its odd, round up, else round down
一旦你得到了数字的小数部分,问题就基本上解决了。 获得小数部分的一种方法是重复从您的数字中减去 2 的幂(假设它已变为正数,如果它一开始是负数)。
下面的函数
getWholeMaker
返回您想要的内容(必须添加以对数字进行四舍五入的“事物”)。 它的运行时间为O(log(n))
,并且仅使用基本运算。Once you have the fractional part of the number, the problem is pretty much solved. One way to get the fractional part is to repeatedly subtract powers-of-2 from you number (assuming it has been made positive, if it were negative to begin with).
The function below,
getWholeMaker
, returns what you want (the "thing" that must be added to round the number). It's running time isO(log(n))
, and uses only elementary operations.如果您不能使用 mod (因为它可能只为您的语言中的整数定义,您也许可以执行类似的操作(在 C 伪代码中):
此解决方案不使用 mod 或任何外部函数。当然,我无法想象你为什么会在现实生活中想要这个,但想想很有趣。
If you can't use mod (because it might only be defined for integers in your language, you might be able to do something like this (in C-ish pseudocode):
This solution doesn't use mod or any outside functions. Of course, I can't imagine why you would want this in real life. It is interesting to think about, though.