2015-11-06 79 views
1

我試圖讓一些事情告訴你兩個圓的交點。我在哪裏放置在圓圈和半徑的中心。 (我從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.45 23687548277813)。這是正確的答案。

任何人都可以告訴我我做錯了什麼或發生了什麼?

回答

1

提示符會將用戶輸入視爲字符串。要將其轉換爲數學爵士樂的整數,請使用parseInt

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

的JavaScript應該「轉換」,如果你因爲JS在執行它的計算是弱類型的數字字符串到整數,但它是很好的做法,你可以通過分析從一個字符串自己的整數值避免一些陷阱。

1

您的提示會返回一個字符串,但您無法對字符串進行數學運算。嘗試將其轉換爲數字:

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

正如Daniel指出的那樣,如果您需要將字符串作爲數字,將字符串更改爲數字總是更好。它似乎很混亂,爲什麼該程序無法正常工作,直到我發現x0被使用了兩次。

程序返回NaN的原因是因爲當使用+運算符時,該數字被轉換爲字符串而不是數字。

這裏發生:x0 + (dx * a/d);

會發生什麼,然後是一個負數被添加到字符串製作類似:2-2

正如你所期望的值不再被轉換成一個數字,從而返回NaN,當我們稍後嘗試減去它時。