这里有一个“纯数学”解
var horizontalSpeed = 1
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = (horizontalSpeed * friction)/(1-friction)
console.log(distance)
或者,如果给定一个“接近于零”,也可以不用循环来完成
var horizontalSpeed = 1
var friction = 0.9
var closeEnoughToZero = 0.001
var distance = 0
// this is the power you need to raise "friction" to, to get closeEnoughToZero
let n = Math.ceil(Math.log(closeEnoughToZero)/Math.log(friction));
// now use the formula for Sum of the first n terms of a geometric series
let totalDistance = horizontalSpeed * friction * (1 - Math.pow(friction, n))/(1-friction);
console.log(totalDistance);
我用
Math.ceil
属于
Math.log(closeEnoughToZero)/Math.log(friction)
-在你的情况下是66。如果在代码中添加了循环计数器,则会看到循环执行66次
而且,正如您所看到的,第二个代码产生的输出与循环完全相同。