2015-10-22 31 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

大声笑有史以来最好的答案... –