首页 > 解决方案 > 使检查的结果始终为真

问题描述

您需要在控制台中始终保持真实)

没有间隙,没有四舍五入,没有改变比较运算符和一般计算逻辑,以及循环条件)

PS这是初中的面试任务...

for (let i = 0; i <= 10; i++) {
  console.log(i + ':' + ((i * 0.1) == (i / 10)));
}
// needed to always true in console.log

标签: javascriptfor-loop

解决方案


我只是创建一个函数来将差异与阈值进行比较,例如0.001

/**
 * Determines if two floating value are equal within a threshold
 * @param {Number} a - First floating value
 * @param {Number} b - Second floating value
 * @param {Number} [t=0.001] - Threshold of difference
 * @return {boolean} Whether the difference is less than the threshold
 */
const equalsFloat = (a, b, t = 0.001) => Math.abs(a - b) < t;

for (let i = 0; i <= 10; i++) {
  console.log(`${i}: ${equalsFloat(i * 0.1, i / 10)}`);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


推荐阅读