돌아가기
이 글은 다음 언어로만 작성되어 있습니다. عربي, English, Español, 日本語, Русский, Türkçe, 简体中文. 한국어 번역에 참여해주세요.

An occasional infinite loop

중요도: 4

This loop is infinite. It never ends. Why?

let i = 0;
while (i != 10) {
  i += 0.2;
}

That’s because i would never equal 10.

Run it to see the real values of i:

let i = 0;
while (i < 11) {
  i += 0.2;
  if (i > 9.8 && i < 10.2) alert( i );
}

None of them is exactly 10.

Such things happen because of the precision losses when adding fractions like 0.2.

Conclusion: evade equality checks when working with decimal fractions.