【问题标题】:Reprompting a user for inputs using a while loop in javascript在javascript中使用while循环重新提示用户输入
【发布时间】:2019-10-30 01:47:26
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • while(!isValidTriangle(one, two, three)) { prompt("Enter lengths") }.
  • 嘿,我重新发布了我的问题并包含了我到目前为止的代码。对不起,我在格式上苦苦挣扎。第一次海报。

标签: javascript while-loop prompt


【解决方案1】:

您可以使用 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;
    }
   }
} 

【讨论】:

  • 谢谢!我有这部分运行顺利。哪里是输入警告的理想位置,告诉用户输入无效并重新输入?我不希望它在第一次运行时出现,所以我不确定如何使用这种结构使其工作。
猜你喜欢
  • 2019-08-03
  • 1970-01-01
  • 2016-03-08
  • 2013-11-16
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2017-01-27
相关资源
最近更新 更多