[英]How to generate array of n equidistant points along a line segment of length x?
I ported this function from a python answer to a similar question on this site.我将此 function 从 python 对本网站上类似问题的回答移植。 However, although the points are equidistant from each other, they are not centered on the line.
但是,尽管这些点彼此等距,但它们并不以直线为中心。
The first point is at 0
while the last is at 83
(the end of the line segment is 100
).第一个点位于
0
处,而最后一个点位于83
处(线段的末端为100
)。
How do I center this row of points?如何使这行点居中?
Specifically, I want the first point to be the same distance from 0
that the last point is from 100
.具体来说,我希望第一个点与
0
的距离与最后一个点与100
的距离相同。
'use strict';
function generatePoints(count, length) {
const points = []
for (let i = 0; i < count; i++) {
const a = i / count;
const x = a * length;
points.push(Math.round(x));
}
return points;
}
const points = generatePoints(6, 100);
console.log(points);
// [ 0, 17, 33, 50, 67, 83 ]
I tried this, but it doesn't appear to work as I expected:我试过这个,但它似乎没有像我预期的那样工作:
for (let i = 0; i < points.length; i++) {
points[i] += (points[1] / 2);
points[i] = Math.round(points[i]);
}
console.log(points);
// [ 9, 26, 46, 63, 80, 96 ]
The first point is 9
away from 0
, but the last point is 4
away from 100
.第一个点距离
0
有9
的距离,但最后一个点距离100
有4
的距离。
Change i / count
to (i + 1) / (count + 1)
.将
i / count
更改为(i + 1) / (count + 1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.