gpt4 book ai didi

javascript - 根据提示存储坐标并计算距离

转载 作者:行者123 更新时间:2023-11-30 00:25:41 25 4
gpt4 key购买 nike

我致力于坐标之间的距离计算,并且构建了一些可以正常工作的东西。

var pointsCoordinates = [[5,7],[5,8],[2,8],[2,10]];
function lineDistance(points) {
var globalDistance = 0;
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}

console.log(lineDistance(pointsCoordinates));

我想稍微改进一下,发送一个提示来存储用户发送的坐标。

例子:

alert(prompt("send me random coordinates in this format [,] and I will calculate the distance))

我想存储这些坐标并用我的函数计算距离。

我知道我必须使用 push 但它不起作用,有人可以帮我写吗?我知道这很简单,但是...我做不到。

非常感谢

最佳答案

工作和测试代码。从提示中获取坐标并将其传递给 lineDistance 函数并将传递的字符串转换为数组。

function lineDistance(points) {
var globalDistance = 0;
var points = JSON.parse(points); // convert entered string to array
for(var i=0; i<points.length-1; i++) {
globalDistance += Math.sqrt(Math.pow( points[i+1][0]-points[i][0] , 2 ) + Math.pow( points[i+1][1]-points[i][1] , 2 ));
}
return globalDistance;
}

var pointsCoordinates = prompt("send me random coordinates in this format [,] and I will calculate the distance");
if (coordinates != null)
console.log(lineDistance(coordinates)); //[[5,7],[5,8],[2,8],[2,10]]
else
alert("Entered value is null");

希望对您有所帮助。

关于javascript - 根据提示存储坐标并计算距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com