1

我正在用 javascript 编写一个简单的三角函数程序,而我的 if 和 while 语句不能正常工作,因为它们只有在第一个条件为真时才会通过,即如果你输入 Sine 它将工作,但如果你输入 Cosine 或 Tangent 则不会。

<script language="JavaScript">
var opposite = 1
var adjacent = 1
var hypotenuse = 1
var sct = "SohCahToa"
while (!(sct == ("Sine" || "Cosine" || "Tangent"))) {
    sct = prompt("Sine (unknown adjacent) / Cosine (unkown opposite side) / Tangent (unknown hypotenuse)")
    if (!(sct == ("Sine" || "Cosine" || "Tangent"))) {
        alert("Spelling error, please try again")
    }
}
if (sct == ("Sine" || "Cosine"))
    hypotenuse = prompt("What is the hypotenuse")
if (sct == ("Sine" || "Tangent"))
    opposite = prompt("What is the opposite side")
if (sct == ("Tangent" || "Cosine"))
    adjacent = prompt("What is the adjacent side")

谢谢(将代码另存为 .html 以进行测试)

4

2 回答 2

5

所有看起来像这样的多重比较:

if (sct == ("Sine" || "Cosine" || "Tangent"))

需要改成这样:

if (sct == "Sine" || sct == "Cosine" || sct == "Tangent")

解释一下,当你这样做时,("Sine" || "Cosine" || "Tangent")that 的评估结果与which 显然不是你想要的相同。"Sine"if (sct == ("Sine" || "Cosine" || "Tangent"))if (sct == "Sine")


这是您应用了所有更正的代码:

var opposite = 1
var adjacent = 1
var hypotenuse = 1
var sct = "SohCahToa"
while (!(sct == "Sine" || sct == "Cosine" || sct == "Tangent")) {
    sct = prompt("Sine (unknown adjacent) / Cosine (unkown opposite side) / Tangent (unknown hypotenuse)")
    (!(sct == "Sine" || sct == "Cosine" || sct == "Tangent")) {
        alert("Spelling error, please try again")
    }
}
if (sct == "Sine" || sct == "Cosine")
    hypotenuse = prompt("What is the hypotenuse")
if (sct == "Sine" || sct == "Tangent")
    opposite = prompt("What is the opposite side")
if (sct == "Tangent" || sct == "Cosine")
    adjacent = prompt("What is the adjacent side")
于 2015-05-21T07:25:23.917 回答
0

我将使用一个数组作为选项,并在下面使用一个 case 语句:

var opposite = 1
var adjacent = 1
var hypotenuse = 1
var sct = "SohCahToa"
var options = ["Sine", "Cosine", "Tangent"];
while (options.indexOf(sct) < 0) {
  sct = prompt("Sine (unknown adjacent) / Cosine (unkown opposite side) / Tangent (unknown hypotenuse)");
  sct = options[options.indexOf(sct)];
  if (options.indexOf(sct) < 0) {
    alert("Spelling error, please try again");
  }
}
switch (sct) {
  case "Sine":
    hypotenuse = prompt("What is the hypotenuse")
    opposite = prompt("What is the opposite side")
    break;
  case "Cosine":
    hypotenuse = prompt("What is the hypotenuse")
    adjacent = prompt("What is the adjacent side")
    break;
  default:
    opposite = prompt("What is the opposite side")
    adjacent = prompt("What is the adjacent side")
}

于 2015-05-21T08:20:18.727 回答