提问人:Dave 提问时间:10/9/2023 更新时间:10/10/2023 访问量:54
99 瓶啤酒 - while + if + else if infinite loops JavaScript?
99 Bottles of Beer - while + if + else if infinite loops JavaScript?
问:
我是编码/编程的新手,目前正在参加在线编码课程。提出的挑战之一是将歌词打印到 99 瓶啤酒歌曲中,我假设你们都知道歌词。我设法想出了一个解决方案(如下)。
目标是控制台日志迭代从 99 到 0,同时保持语法正确。
我的问题是,为什么设置 while (endBeerCount >= 0) 会导致啤酒计数在无限循环中变为负数?
设置 while (endBeerCount >= 1) 可修复无限循环并正确记录歌词。为什么这种情况不会导致无限循环?
这是我的代码:
var beerCount = 99;
var endBeerCount = 98;
function bottlesOfBeer() {
while (endBeerCount >= 0) { // >=0 causes infinite loop (beer counts go negative). >=1 works
if (endBeerCount > 1) {
console.log(beerCount + " bottles of beer on the wall " + beerCount + " bottles of beer." +
"Take one down and pass it around " + endBeerCount + " bottles of beer on the wall.");
beerCount--;
endBeerCount--;
}
else if (endBeerCount = 1) {
beerCount--;
endBeerCount--;
console.log(beerCount + " bottle of beer on the wall " + beerCount + " bottle of beer. "
+ "Take one down and pass it around no more bottles of beer on the wall.");
}
}
return console.log("No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more 99 bottles of beer on the wall.");
}
答: 暂无答案
评论
=
用于为变量赋值。 并用于比较。因此,将值 1 分配给变量。==
===
if (endBeerCount = 1)
beerCount--; endBeerCount--;