2017-10-17 56 views
-1

我有一個號碼列表var coins = [16, 8, 4, 2, 1];,我應該讓用戶輸入一個號碼,然後找出需要的數字組合才能使用戶輸入的號碼相同,然後將該信息顯示給用戶(例如,多少次您使用任何給定的數字。)計算while循環運行多少次。 javascript

這裏的代碼。

//list of numbers, and the variable that will hold the math for the program 
var coins = [16, 8, 4, 2, 1]; 
var value = 0; 

//ask the user for a number 
var number = Number(prompt('please enter a number between 20 and 100.')); 

//counting loops and list locations 
var i = 0; 
var count = 0; 

//filter out numbers under 20 and over 100 
if (number < 20 || number > 100){ 
    alert("Invalid number"); 
} 


while (value != number) { 
    //run the loop while a number from the list + the value is less than or equal to the number the user entered 
    while(coins[i] + value <= number){ 
     value += coins[i]; 
     console.log(coins[i]); 

     //count how many times the loop runs. currently its only doing the first position of the list which seems wrong. 
     if (coins[i] == coins[0]){ 
      count++; 
     } 
    } 
    i++; 
} 

console.log(value); 
console.log(number); 
console.log(i); 
console.log(count); 

我要計算時間使用每個號碼數,但我真的不能算循環運行,因爲他們有時會在循環不同數量從而使計數++錯誤的次數。在鉻控制檯日誌console.log(coins[i]);顯示硬幣[我]號碼旁邊的一個小數字,這個數字到底是什麼,我怎麼去得到它,因爲它似乎正是我所需要的。

有權不我只是用

if (coins[i] == coins[0]){ 
     count++; 
    } 

,因爲我不認爲這是一個數,這將導致除了第一個號碼16重複任何但是這種感覺就像一個廉價的解決辦法。

+0

您的循環應該正好運行coins.length次。而且你最好使用for循環。目標是找出每個硬幣(從最大開始)與用戶輸入的數字相匹配的次數。你知道你的算法是在你到達硬幣'1'時完成的,因爲它匹配了沒有被大硬幣覆蓋的剩餘金額。我還建議把硬幣放在一個物體上,然後用它來存儲硬幣需要多少次。因此,例如數字= 50,硬幣對象將是:{16:3,8:0,4:0,2:1,1:0}; – timotgl

+0

'[number >> 4,(number&8)>> 3,(number&4)>> 2,(number&2)>> 1,number&1]' – ASDFGerte

+0

@bittercold您能接受答案嗎? – aaron

回答

0

您可以創建一個字典計數器並初始化它像這樣:

var num = {}; 
coins.forEach(function (coin) { 
    num[coin] = 0; 
}); 

用法:

while (value != number) { 
    while(coins[i] + value <= number){ 
     value += coins[i]; 
     num[coins[i]]++; 
    } 
} 

console.log(num); 
0

使用這樣一個對象:

var counts = {"16":0, "8":0, "4":0, "2":0, "1":0} 

取而代之的是單一的int count然後用作:

counts[i]++; 
0

我想你是問如何得到每個數字被使用多少次。

如果輸入是20,則使用16次,使用4次一次。

顯然,您需要5個計數器用於{16,8,4,2,1}中的每個數字。

您將需要申報

var countCoins = [0, 0, 0, 0, 0]; 

,而不是和

if (coins[i] == coins[0]){ 
     count++; 
    } 

countCoins[i]++; 

最後,countCoins [I]將有次數是使用硬幣[i]

您可以決定將它們全部加在一起或將它們分開。