我有一個號碼列表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重複任何但是這種感覺就像一個廉價的解決辦法。
您的循環應該正好運行coins.length次。而且你最好使用for循環。目標是找出每個硬幣(從最大開始)與用戶輸入的數字相匹配的次數。你知道你的算法是在你到達硬幣'1'時完成的,因爲它匹配了沒有被大硬幣覆蓋的剩餘金額。我還建議把硬幣放在一個物體上,然後用它來存儲硬幣需要多少次。因此,例如數字= 50,硬幣對象將是:{16:3,8:0,4:0,2:1,1:0}; – timotgl
'[number >> 4,(number&8)>> 3,(number&4)>> 2,(number&2)>> 1,number&1]' – ASDFGerte
@bittercold您能接受答案嗎? – aaron