0

该循环应该获取每本书的价格,将其添加到总数中,然后将平均值放在每本书的页面上,直到用户输入“N”

<script type="text/javascript">
var ct = 1;
var yesORno = "Y";
while (yesORno = "Y"){
    book = prompt("What is the price of book #" + ct, 0);
    total = parseInt(book) + total;
    ans = total / ct;
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>");
    ct = ct + 1;
    yesORno = prompt("Would you like to continue? (Y/N)", "")
}
</script>
4

3 回答 3

8

您应该将您的 while 条件更改为:

while (yesORno == "Y")

使用 only=将使其将“Y”值分配给 yesORno 并返回自身,这被评估为 true 并使其永远运行。

于 2013-10-28T01:20:31.473 回答
3
var ct = 1;
var yesORno = "Y";
while (yesORno == "Y"){
    book = prompt("What is the price of book #" + ct, 0);
    total = parseInt(book) + total;
    ans = total / ct;
    document.write("<p>With book #" + ct +" The average is " + ans + "</p>");
    ct = ct + 1;
    yesORno = prompt("Would you like to continue? (Y/N)", "")
}

看第三行。

于 2013-10-28T01:20:41.630 回答
3

像其他人所说的那样,您使用了赋值运算符=而不是相等运算符==或严格相等运算符===

但是,您也可以改用 do while 循环重构您的代码。这将消除拥有yesORno变量的需要。

do {
    //...
} while(prompt("Would you like to continue? (Y/N)", "") === 'Y')
于 2013-10-28T01:28:38.683 回答