而在JavaScript中循环,陷入无限循环

时间:2016-03-07 17:58:26

标签: javascript

这是我的代码。我目前陷入无限循环。该计划必须询问每天收集的瓶子数量7次。所以循环应该迭代7次。然后,我必须在最后显示总瓶数和每瓶的总支出(乘以.10)。

function main() {
    alert("Welcome to the program");
    var totalBottles = 0;
    var todayBottles = 0;
    var totalPayout = 0;
    var keepGoing = "y";
    var counter = 1;
    while (keepGoing == "y")
        getBottles(totalBottles, todayBottles, counter);
    calcPayout(totalPayout, totalBottles);
    printInfo(totalBottles, totalPayout);
    keepGoing = prompt("Do you want to keep going? Enter y for yes");
}

function getBottles(totalBottles, todayBottles, counter) {
    while (counter < 7) {
        todayBottles = prompt("Enter the number of bottles returned for the day");
        totalBottles = (totalBottles + todayBottles);
        counter = (counter + 1);
    }
}

function calcPayout(totalPayout, totalBottles) {
    totalPayout = 0;
    totalPayout = (totalBottles * 0.10);
}

function printInfo(totalBottles, totalPayout) {
    alert("The total number of bottles returned is", totalBottles);
    alert("The total paid out is", totalPayout);
}
//calls main
main();
alert("End of program");

2 个答案:

答案 0 :(得分:0)

//请尝试了解它正在做什么以及为什么您的代码无法打印正确的信息。

function main() {
    alert("Welcome to the program");

    var totalBottles = 0;
    var todayBottles = 0;
    var totalPayout = 0;
    var keepGoing = "y";
    var counter = 1;

    while (keepGoing == "y") {
        totalBottles = getBottles(totalBottles, todayBottles, counter);
        totalPayout = calcPayout(totalPayout, totalBottles);
        printInfo(totalBottles, totalPayout);
        keepGoing = prompt("Do you want to keep going? Enter y for yes");
    }
}


function getBottles(totalBottles, todayBottles, counter) {
    while (counter < 7) {
        todayBottles = prompt("Enter the number of bottles returned for the day");
        //alert(todayBottles);
        totalBottles += parseInt(todayBottles);
        //alert(totalBottles);
        counter = (counter + 1);
    }
    return totalBottles;
}

function calcPayout(totalPayout, totalBottles) {
    totalPayout = 0;
    totalPayout = (totalBottles * 0.10);
    return totalPayout;
}

function printInfo(totalBottles, totalPayout) {
    alert("The total number of bottles returned is " + totalBottles);
    alert("The total paid out is " + totalPayout);
}

//calls main
main();
alert("End of program");

答案 1 :(得分:0)

刚刚放下{after while(keepGoing ==“y”) 因为根据你的代码你的while循环体只包含一行         getBottles(totalBottles,todayBottles,计数器); 所以你的程序停留在那一行,因为keepGoing始终为True