在 javascript 中使用 while 循环重新提示用户输入

Reprompting a user for inputs using a while loop in javascript

我不熟悉编码和尝试一些作业。我正在尝试提示用户输入三角形边的长度。该程序计算面积和 returns 一个值。如果给定的长度没有创建三角形,我正在尝试使用 while 循环重新提示用户。

While (true)
{
    SideA = parseFloat(prompt("Enter the length of Side A"));
    SideB = parseFloat(prompt("Enter the length of Side B"));
    SideC = parseFloat(prompt("Enter the length of Side C"));

    //Calculate half the perimeter of the triangle
    S = parseFloat(((SideA+SideB+SideC)/2));

    //Calculate the area
    Area = parseFloat(Math.sqrt((S*(S-SideA)*(S-SideB)*(S-SideC))));

    if(isNaN(Area)) 
    {
        alert("The given values do not create a triangle. Please re- 
           enter the side lengths.");
    } 
    else 
    {
        break;
    }   

}

//Display results
document.write("The area of the triangle is " + Area.toFixed(2) + "." 
+ PA);

您可以使用 do while 循环来实现:

function checkTriangleInequality(a, b, c) {
   return a < b + c && b < c + a && c < b + a;
}

function promptSides() {
  let a, b, c;
   while (true) {
    a = parseFloat(prompt("Enter a"));
    b = parseFloat(prompt("Enter b"));
    c = parseFloat(prompt("Enter c"));

    if (!checkTriangleInequality(a, b, c)) {
      alert("Input is invalid, please try again.")
    } else {
      let s = (a+b+c)/2
      let area = parseFloat(Math.sqrt((s*(s-a)*(s-b)*(s-c))));
      console.log(area);
      break;
    }
   }
}