gpt4 book ai didi

javascript - while 循环不执行或不循环?

转载 作者:行者123 更新时间:2023-11-30 16:04:43 26 4
gpt4 key购买 nike

// require '04_wonky_coins'
// require 'rspec'
//
// # Catsylvanian money is a strange thing: they have a coin for every
// # denomination (including zero!). A wonky change machine in
// # Catsylvania takes any coin of value N and returns 3 new coins,
// # valued at N/2, N/3 and N/4 (rounding down).
// #
// # Write a method `wonky_coins(n)` that returns the number of coins you
// # are left with if you take all non-zero coins and keep feeding them
// # back into the machine until you are left with only zero-value coins.
// #
// # Difficulty: 3/5
//
// describe "#wonky_coins" do
// it "handles a coin of value 1" do
// wonky_coins(1).should == 3
// end
//
// it "handles a coin of value 5" do
// wonky_coins(5).should == 11
// # 11
// # => [2, 1, 1]
// # => [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
// # => [[[0, 0, 0], 0, 0], [0, 0, 0], [0, 0, 0]]
// end
//
// it "handles a coin of value 6" do
// wonky_coins(6).should == 15
// end
//
// it "handles being given the zero coin" do
// wonky_coins(0).should == 1
// end
// end
function check_coins(hand){
for(var i=0; i<hand.length; i++){
var coin = hand[i]
if(coin !==0){
return i;
} else {
return null;
}
}
return false;
}


function wonkyCoins(n){
var hand = [];

hand.push(Math.floor(n/2));
hand.push(Math.floor(n/3));
hand.push(Math.floor(n/4));




while(check_coins(hand){

var indx = check_coins(hand);


var value = hand[indx];

var index1 = hand.indexOf(hand[indx]);

if (index1 > -1) {
hand.splice(index1, 1);
}


hand.push(Math.floor(value/2));
hand.push(Math.floor(value/3));
hand.push(Math.floor(value/4));

}

return hand.length;

}

程序运行正常,但 while 循环由于某些原因没有循环。我怀疑条件有问题。我不确定 javaScript 是否接受这种条件。但是,在 ruby​​ 中它起作用了。有人可以为我解释为什么不起作用吗?

最佳答案

您错过了一个圆括号来关闭您的 while 循环条件参数。您的代码实际上应该是:

while(check_coins(hand)){

...

}

如果这不起作用,则可能是条件本身。尝试:

while(check_coins(hand) !== null){

...

}

关于javascript - while 循环不执行或不循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com