作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
作为我对 this question 的回答的延伸,我试图以这样的方式拆分一个实数,即两个数字中的每一个在最后一位数字上相差最多 1(受浮点算术表示的限制)。
例如:
7 => 4, 3
7.2 => 3.6, 3.6
7.3 => 3.7, 3.6 (or 3.5999999999999996) -- I understand this is a corner case and it is alright
7.25 => 3.63, 3.62
7.225 => 3.613, 3.612
需要说明的是,生成的加数必须包含与原始数字相同的位数。
这是我到目前为止想出的。
var x = 7.3;
if(x != Math.round(x)) {
var p1 = Math.ceil((x / 2) * 10) / 10;
} else {
var p1 = Math.ceil(x / 2);
}
var p2 = x - p1;
console.log(p1, p2);
截至目前,这适用于整数和小数点后一位小数。我相信一般的解决方案将涉及弄清楚点后出现多少位数字。
我不确定如何做到这一点,但我相信一种解决方案是转换为字符串,在 '.'
上拆分,找到位数,然后乘以/除以适当的10 的幂...基本上扩展了我编写的代码,因此它适用于任意数字。
首选 Javascript 解决方案,但 python 解决方案也可以。任何帮助,将不胜感激。谢谢!
最佳答案
快速完成,它是否符合您的需求?
function GenerateAddends(n){
if(n == Math.round(n)){
return [Math.round(n/2),n-Math.round(n/2)];
}else{
var len = n.toString().split(".")[1].length
return [
Math.round(n/2 * Math.pow(10,len)) / Math.pow(10,len),
n - Math.round(n/2 * Math.pow(10,len)) / Math.pow(10,len)
]
}
}
console.log(GenerateAddends(7))
console.log(GenerateAddends(7.2))
console.log(GenerateAddends(7.3))
console.log(GenerateAddends(7.25))
console.log(GenerateAddends(7.225))
或者使用 ECMAScript 2016:
function GenerateAddends(n){
if(n == Math.round(n)){
return [Math.round(n/2),n-Math.round(n/2)];
}else{
var len = n.toString().split(".")[1].length
return [
Math.round(n/2 * 10**len) / 10**len,
n - Math.round(n/2 * 10**len) / 10**len
]
}
}
console.log(GenerateAddends(7))
console.log(GenerateAddends(7.2))
console.log(GenerateAddends(7.3))
console.log(GenerateAddends(7.25))
console.log(GenerateAddends(7.225))
你会发现,我和你的想法是一样的,转成字符串,得到小数位数。
关于javascript - 将实数拆分为 2 个加数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246600/
我是一名优秀的程序员,十分优秀!