圆的面积

Area of the circle

所以我创建了一个 .js 文件来计算圆的面积,而 calculateArea() 需要计算它。 它唯一做的就是 prompt()。我做错了什么?

function calculateArea(myRadius){
  var area = (myRadius * myRadius * Math.PI);
  return area;

  function MyArea(){
    calculateArea(myRadius);
    alert("A circle with a " + myRadius + 
          "centimeter radius has an area of " + area + 
          "centimeters. <br>" + myRadius + 
          "represents the number entered by the user <br>" + area +
          "represents circle area based on the user input.");  
  }      
}
var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:",0));
calculateArea(myRadius);

您需要将函数 MyArea 保留在 calculateArea 外部,并从 MyArea.

内部调用 calculateArea

调用 MyArea 函数而不是 calculateArea

示例代码段:

function calculateArea(myRadius) {
  return (myRadius * myRadius * Math.PI);
}

function MyArea() {
  var area = calculateArea(myRadius);
  alert("A circle with a " + myRadius + "centimeter radius has an area of " + area + "centimeters. <br>" + myRadius + "represents the number entered by the user <br>" + area + "represents circle area based on the user input.");


}

var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:", 0));
MyArea(myRadius);

PS:有更好的方法来做到这一点。如有问题请评论。

您基本上需要在 calculateArea 之外调用 MyArea 但在这种情况下,为什么不这样呢?

function calculateArea(myRadius) {
    return myRadius * myRadius * Math.PI;
}

var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:",0));
var area = calculateArea(myRadius);

alert("A circle with a " + myRadius + "centimeter radius has an area of " + area + "centimeters. <br>" + myRadius + "represents the number entered by the user <br>" + area + "represents circle area based on the user input.");

以下为单功能方案:

function MyArea(myRadius){

 var area = Math.pow(myRadius, 2) * Math.PI;
  
 alert(
     "A circle with a " + myRadius +
     "centimeter radius has an area of " +
     area + "centimeters. \n" + myRadius +
     "represents the number entered by the user \n" +
     area + "represents circle area based on the user input."
 );
}

var myRadius = parseFloat(prompt("Enter the radius of your circle in cm:", 0));

MyArea(myRadius);

这是一种计算圆面积的方法

let Area, Environment;
let Radius = prompt("Enter Radius ");

function calculate(Radius) {
  CalEnvironment(Radius);
  CalArea(Radius);
}
function CalEnvironment(Radius) {
  Environment = Radius * 3.14 * 2;
  console.log("Environment is : " + Environment);
}
function CalArea(Radius) {
  Area = Radius * Radius * 3.14;
  console.log("Area is : " + Area);
}
calculate(Radius);