gpt4 book ai didi

javascript - UserInput 搞乱了一个函数

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

我试图做一些东西来告诉你两个圆的交点。我放在圆心和半径的地方。 (我从 stackoverflow 得到了交集函数:here)。我正在尝试添加用户输入,但是每当我将代码中的静态数字更改为用户输入(通过提示或 html 输入)时,函数就会中断并且警报会向我发送未完成的答案和 Nan。

这是到目前为止的编码(没有用户输入):

    <html>
<button onclick="button()">Test</button>
<script>
var x0 = 3;
var y0 = 0;
var r0 = 3;
var x1 = -1;
var y1 = 0;
var r1 = 2;
function button() {


intersection(x0, y0, r0, x1, y1, r1)

function intersection(x0, y0, r0, x1, y1, r1) {
var a, dx, dy, d, h, rx, ry;
var x2, y2;

/* dx and dy are the vertical and horizontal distances between
* the circle centers.
*/
dx = x1 - x0;
dy = y1 - y0;

/* Determine the straight-line distance between the centers. */
d = Math.sqrt((dy*dy) + (dx*dx));

/* Check for solvability. */
if (d > (r0 + r1)) {
/* no solution. circles do not intersect. */
return false;
}
if (d < Math.abs(r0 - r1)) {
/* no solution. one circle is contained in the other */
return false;
}

/* 'point 2' is the point where the line through the circle
* intersection points crosses the line between the circle
* centers.
*/

/* Determine the distance from point 0 to point 2. */
a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ;

/* Determine the coordinates of point 2. */
x2 = x0 + (dx * a/d);
y2 = y0 + (dy * a/d);

/* Determine the distance from point 2 to either of the
* intersection points.
*/
h = Math.sqrt((r0*r0) - (a*a));

/* Now determine the offsets of the intersection points from
* point 2.
*/
rx = -dy * (h/d);
ry = dx * (h/d);

/* Determine the absolute intersection points. */
var xi = x2 + rx;
var xi_prime = x2 - rx;
var yi = y2 + ry;
var yi_prime = y2 - ry;

var list = "(" + xi + ", " + yi + ")" + "(" + xi_prime + ", " +
yi_prime + ")"
alert(list);
}
}

</script>
</html>

当我将圆圈之外的任何变量更改为用户输入时,例如:

    var x0 = prompt("X cord of circle 1");

警报显示为:(3-2.6250, -1.4523687548277813)(NaN, 1.4523687548277813)

如果没有用户输入(显示在大代码块中),它会显示为:(0.375, -1.4523687548277813)(0.375, 1.4523687548277813)。这是正确答案。

谁能告诉我我做错了什么或发生了什么事?

最佳答案

Prompt 会将用户输入作为字符串。要将其转换为数学爵士乐的整数,请使用 parseInt

 var x0String =  prompt("X cord of circle 1");
var x0 = parseInt(x0String);

如果你对它执行计算,JavaScript 应该将数字字符串“转换”为整数,因为 JS 是弱类型的,但这是一个很好的做法,你可以通过自己解析字符串中的整数值来避免一些陷阱。

关于javascript - UserInput 搞乱了一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33575161/

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