2016-03-07 172 views
-3

這是我的代碼。我目前陷入無限循環。該計劃必須詢問每天收集的瓶子數量,共7次。所以循環應該迭代7次。然後,我必須在每個瓶子上顯示總瓶數和總支出(最終乘以10)。雖然在JavaScript中的循環,陷入無限循環

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"); 
+4

你錯過了第一個函數中while循環體的'{}'。學習使用縮進來闡明你的代碼結構。 – Pointy

+0

這就是爲什麼正確的格式化非常重要。請更細心。 – ndugger

+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"); 
+0

謝謝!我現在有問題返回值?當我試圖把回報放在裏面時,就打破了整個事情。我如何讓它保持並傳遞值,以便最終計算出來? –

+0

非常感謝Zain。我是一名初學者,努力學習我能做到的最好! –

0

只是把{後 而(keepGoing == 「Y」) 因爲根據你的代碼while循環體中包含只有一行 getBottles(totalBottles,todayBottles,計數器); 所以你的程序被卡在那條線上,因爲keepGoing總是爲真