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

标签 javascript while-loop prompt

我不熟悉编码和尝试一些作业。我正在尝试提示用户输入三 Angular 形边的长度。该程序计算面积并返回一个值。如果给定的长度没有创建三 Angular 形,我正在尝试使用 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;
    }
   }
} 

关于javascript - 在javascript中使用while循环重新提示用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614831/

相关文章:

javascript - 如何围绕现有的 Javascript 库创建 Angular 包装器?

Javascript:通过引用传递对象

php - 我可以使用 window.open 打开现有的 php 文件并将 javascript 变量传递给该 php 页面吗?

Python - 为什么我们必须在 while 循环中而不是在 for 循环中初始化标识符?

git - 在 bash 提示符下为 git status 设置颜色

javascript - Alertify 不会因提示而停止

javascript - ExtJS Reactor 样板安装错误(index.html 未找到)!

python - 如何在满足 while 循环条件时跳出 time.sleep()

java - Java Fencepost/While 循环条件测试简介

javascript - 为什么提示后会执行音频?