一 常规比较
let n = 0;
while(true){
n += 0.1;
if(n === 0.3 ) break;
console.log(`This is ${n}`);
}
console.log(`stopped at ${n}`);
会无限循环下去
二、改进
let n = 0;
while(true){
n += 0.1;
if(Math.abs(n - 0.3) < Number.EPSILON) break;//利用内置的极小数来判断 首先求绝对值,相减与极小值比较即可
console.log(`This is ${n}`);
}
console.log(`stopped at ${n} ${Number.EPSILON}`);
网友评论