试图制作一个javascript程序来计算球体的体积

时间:2015-10-22 04:28:26

标签: javascript

    // 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;

我正在尝试制作一个脚本来计算球体的体积。这是一个家庭作业,所以那些评论都在那里。它基本上告诉我该怎么做。

我尽我所知遵循它,但我仍然收到错误。我得到的错误是第30行的“SyntaxError:missing; before statement”。这告诉我放一个;在“结束如果”之前。我猜这不是错误。我猜这个公式是错误的。

2 个答案:

答案 0 :(得分: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作为对pi的估算,请使用Math.PI

另一方面,您的代码无效的原因是因为end if不是javascript代码。您应该将其删除,然后重新测试您的代码。

这是一个工作小提琴:https://jsfiddle.net/qm6uaapu/

答案 1 :(得分:0)

如果

,请删除结尾

因为: 1.它在Javascript中不存在。 2. if的结束括号“}”已经结束你的if语句。