2015-10-22 34 views
0
// sphere.js #2 
// This script calculates the volume of a sphere. 

// Function called when the form is submitted. 
// Function performs the calculation and returns false. 
function calculate() { 
    'use strict'; 

    // For storing the volume: 
    var volume; 

    // Task 1: Get a reference to the form element: 
    var radius = document.getElementById("radius"); 

    // Add an "if" statement here to 
    // make sure there is a reference 
    if (radius) { 
     //Task #2: Add an "if" to make sure the value is positive: 
     if (radius > 0) { 
      // Task #3: Perform the calculation: 
      volume = (4/3)*(22/7)*(Pow(radius,3)); 
      //HINT: the formula for the volume of a sphere is V=(4/3)*(pi)*(radius cubed) 

      // Format the volume: 
      volume = volume.toFixed(4); 

      // Task #4: Display the volume: 
      document.getElementById("volume").id ="volume"; 
      //Hint: use the same method as in the radius variable assignment call above 
     } //End if 
    } end if radius 

    // Return false to prevent submission: 
    return false; 

} // End of calculate() function. 

// Function called when the window has been loaded. 
// Function needs to add an event listener to the form. 
function init() { 
    'use strict'; 
    document.getElementById('theForm').onsubmit = calculate; 
} // End of init() function. 
window.onload = init; 

我想製作一個腳本來計算球體的體積。它是一項家庭作業,這就是爲什麼所有這些評論都在那裏。它基本上告訴我該怎麼做。試圖製作一個JavaScript程序來計算球體的體積

那麼我遵循它的最好的我的知識,但我仍然得到一個錯誤。我得到的錯誤是第30行的「SyntaxError:missing; before statement」。這是告訴我把一個;之前「結束如果」。我猜這不是錯誤。我猜測公式就是錯誤。

+1

條件由右括號「結束」。你應該完全擺脫「如果半徑結束」。 – rnevius

+0

您需要採用radius元素的'.value'。另外,「Pow」是什麼?有沒有理由不使用'Math.PI'? –

+2

Javascript中沒有'end if'語句。這應該是一個評論。 – jfriend00

回答

1

這是計算球的體積公式:

enter image description here

考慮到這一點,

function volumeOfSphere(radius) { 
    return (4/3)*Math.PI*Math.pow(radius,3); 
} 

console.log('The volume of a sphere with a radius of 5 is: '+volumeOfSphere(5)); 

另外,請不要使用22/7作爲估計圓周率,請使用Math.PI

另一方面,你的代碼不工作的原因是因爲end if不是JavaScript代碼。你應該刪除它,並重新測試你的代碼。

這裏是工作提琴:https://jsfiddle.net/qm6uaapu/

+0

這是正確的,但它並沒有解釋問題中提到的錯誤,或者解決了OP代碼中與從html元素獲取/設置值有關的其他問題。 – nnnnnn

+0

我改變了,但現在我認爲唯一的問題是任務#4,顯示音量。因爲當我點擊計算時,我沒有控制檯錯誤,但它不顯示音量。編輯:答案不應該顯示在控制檯中。它的HTML形式。我應該使用DOM來替換原始「卷」ID與窗體上更新的卷ID以顯示答案, – BreeBreeBRAN

+0

這可能是因爲你的代碼有錯誤。 javascript中沒有'end if'這樣的東西。刪除它 –

0

刪除結束時,如果

因爲: 1.它不會在Javascript中存在。 2.右括號「}」if已經結束了你的if語句。

+0

大聲笑有史以來最好的答案... –