You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

99瓶啤酒歌词打印:为何while(endBeerCount>=0)引发无限循环?

《99瓶啤酒》歌词打印代码的无限循环问题

我是编程新手,正在参加在线编程课程。其中一项挑战是打印《99瓶啤酒》的歌词,默认大家知晓歌词内容。我编写了如下解决方案,目标是在console中打印从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. 致命的赋值运算符错误

你的代码里有个关键语法错误:else if (endBeerCount = 1)这里用的是赋值运算符=,而非比较运算符==或===。这个错误直接触发了无限循环:

  • 当endBeerCount的值变为0时,第一个if (endBeerCount > 1)条件不成立,进入else if分支。
  • endBeerCount = 1会把endBeerCount强制设为1,同时这个表达式的返回值是1(非布尔值但会被视为true),所以每次都会进入该分支。
  • 进入分支后,执行beerCount--和endBeerCount--,endBeerCount又变回0。
  • 下一次循环时,endBeerCount >= 0条件成立,重复上述过程:赋值为1→减到0→赋值为1……无限循环,同时beerCount会不断递减变成负数。

2. >=1条件为何能正常工作

当循环条件改成while (endBeerCount >= 1)时:

  • 循环会在endBeerCount变为0时直接终止,不会触发那个错误的else if分支。
  • 所有迭代只会执行if (endBeerCount > 1)的分支,不会出现无限循环的情况。

修复建议

把else if里的赋值运算符改成比较运算符:

else if (endBeerCount === 1)

这样无论循环条件是>=0还是>=1,都能正确执行,不会出现无限循环。

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:20:27