美文网首页
双精度小数如何比较 2019-01-23

双精度小数如何比较 2019-01-23

作者: 二十一克拉灵魂 | 来源:发表于2019-01-23 09:17 被阅读0次

一 常规比较

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}`);

相关文章

网友评论

      本文标题:双精度小数如何比较 2019-01-23

      本文链接:https://www.haomeiwen.com/subject/myadjqtx.html