while循环不能在javascript中工作

时间:2016-10-25 17:19:22

标签: javascript

我在使用此代码时遇到了一些麻烦。我认为它与while循环有关。此外,我是JavaScript的新手,所以,如果您对如何改进语法或使我的代码更有效提出任何建议,我们将不胜感激。

代码应如何运作。  用户输入项目的成本,然后输入金额  钱给了。该计划将找出变化所需的季度,硬币,镍币,硬币的数量变化。

运行时会发生什么 弹出两个提示框,而不是我收到警告警告..

"此页面上的脚本可能正忙,或者可能已停止响应。您可以立即停止脚本,在调试器中打开脚本,或者让脚本继续运行。"

https://jsfiddle.net/krighty78/g44ejnbw/1/



    /* The user enters a cost of an item and then the amount of
         money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change.*/


    var cost = prompt('please enter total cost of the item without tax');
    cost = parseFloat(cost);

    var moneyGiven = prompt('please enter the amount of money given');
    moneyGiven = parseFloat(moneyGiven);

    var tax = 0.15;
    tax = (cost * tax);

    var quarter = 0;
    var dime = 0;
    var nickel = 0;
    var penny = 0;

    var q = 0.25;
    var d = 0.10;
    var n = 0.05;
    var p = 0.01;
    var change = (moneyGiven - (cost + tax));
    console.log(change);

    while (change > 0) {

      if (change >= q) {
        change - q;
        quarter++;
      } else if (change >= d) {
        change - d;
        dime++;
      } else if (change >= n) {
        change - n;
        nickel++;
      } else if (change >= p) {
        change - p;
        penny++;
      }

    }; //while loop

    console.log(quarter);
    console.log(dime);
    console.log(nickel);
    console.log(penny);




1 个答案:

答案 0 :(得分:0)

while循环没问题,问题出在语句

change - q;
change - d;
change - n;
change - p;

您没有更新change的值。将这些更改为:

change = change - q;
change = change - d;
change = change - n;
change = change - p;