繁体   English   中英

计算 while 循环运行的次数。 javascript

[英]Count how many times a while loop runs. javascript

我有一个数字列表var coins = [16, 8, 4, 2, 1]; 我应该要求用户输入一个数字,然后找出与用户输入的数字相等所需的数字组合,然后向用户显示该信息(例如,您使用任何给定数字的次数。)

这是代码。

//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);

我想计算每个数字被使用的次数,但我无法真正计算循环运行的次数,因为它们有时在循环中是不同的数字,从而使 count++ 出错。 在 chrome 控制台日志console.log(coins[i]); 在 coins[i] 数字旁边显示一个小数字,该数字究竟是什么以及我将如何获取它,因为它似乎正是我所需要的。

正确的不是我只是在使用

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

因为我认为除了第一个数字 16 之外,没有一个数字会导致任何重复,但这感觉像是一种廉价的解决方法。

我想您是在问如何获得每个数字的使用次数。

就像输入是 20 一样,16 使用一次,4 使用一次。

显然,{16, 8, 4, 2, 1} 中的每个数字都需要 5 个计数器。

你需要申报

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

而不是

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

countCoins[i]++;

最后,countCoins[i] 将有使用 coin[i] 的次数

您可以决定将它们全部添加在一起或将它们分开。

您可以创建一个字典计数器并像这样初始化它:

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);

使用这样的对象:

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

而不是单个 int count ,然后用作:

counts[i]++;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM