javascript - 使检查的结果始终为真
问题描述
您需要在控制台中始终保持真实)
没有间隙,没有四舍五入,没有改变比较运算符和一般计算逻辑,以及循环条件)
PS这是初中的面试任务...
for (let i = 0; i <= 10; i++) {
console.log(i + ':' + ((i * 0.1) == (i / 10)));
}
// needed to always true in console.log
解决方案
我只是创建一个函数来将差异与阈值进行比较,例如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; }
推荐阅读
- spring - #sets.contains 来自 thymeleaf 总是返回 false
- c# - 通过 .NET c# 更新 SQL 数据库,仅进行更改
- android - 如何在 Android/iOS 上调试 Rust?
- javascript - 一个接受字符串并将输入中第二高的数字作为整数返回的函数
- javascript - 使用大参数时平滑滚动功能出现故障
- postgresql - Gorm 仅在条目不存在时创建
- python - 如何使用 Numpy 重塑?
- angular - 当我重复调用 API 时如何/在哪里检查 http 错误?
- xml - 使用 PL/SQL 将 XML 文件拆分成小块
- r - 过滤循环以创建多个数据框