JavaScript 99Bottles - 无限循环

问题描述 投票:0回答:4

(我已经知道这不是 99 瓶代码挑战的最优雅的解决方案,但我真的很想知道将来如何不重复这个错误。)

当它在控制台中运行时,它会重复

(count === 0)
条件,并且除了
"0 bottles of beer"
控制台日志之外不重复任何内容,直到崩溃。

我尝试在计数减至 0 后使用“break”语句,但没有取得任何成功。

let count = 99;

function bottlesOfBeer() {
    while (count >= 0) {
        if (count > 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
            count--;
            console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");  
        };

        if (count === 0) {
            console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
        } //*this is where I tried the break statement*
    }
};

bottlesOfBeer();

javascript while-loop infinite-loop break decrement
4个回答
4
投票

仅当

count
大于 0 时才递减,因此它永远不会低于 0;但只要
count >= 0
,循环就会继续。


2
投票

这是更正后的代码:

function bottlesOfBeer() {
  var count = 99;
  while (count > 0) {
    console.log(count + " bottles of beer on the wall, " + count + " bottles of beer,");
    count--;
    console.log(" take one down, pass it around, " + count + " bottles of beer on the wall.");  
  }
  console.log(count + " bottles of beer on the wall, " + count + " bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.");
};

bottlesOfBeer();

请阅读并理解 - 如果您有疑问,请询问。
在代码中,

count
设置为99。
while
变为零时,
count
循环停止。
当循环存在时,
count
为零,并且记录歌曲的相应行。
我已经删除了空行...
除此之外 - 你的代码非常整洁:没有奇怪的缩进(你不会相信我所看到的 - 并不是它会影响执行,只是更容易阅读)。


1
投票

while (count >= 0)
变成
while (count > 0)
就可以开始了!

问题是,当它达到零时,您只需记录消息而不再减少它,因此它保持为零并且

(count >= 0)
始终为真。


0
投票
*let x = 99
let y = x - 1
function beer() {
    while (x > 1) {
        x--
        y--
        console.log(x + " bottles of bear on the wall, " + x + " bottles of bear. Take one down and pass it around, " + y + " bottles of bear on the wall.")
    }
}*
© www.soinside.com 2019 - 2024. All rights reserved.