实现说明
文件的主干是一个循环——for (const v of values)。
values 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
round(-2.5) =、round(-0.5) =、trunc(-2.9) =——输出的每一行都能指回产生它的那次调用。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 文件用顶层绑定保存自己的状态:values。
核心语句
const values = [2.7, -2.7, 2.3, -2.3];
代码示例
// The three rounding functions agree on positives and diverge on negatives: floor toward -Infinity, trunc toward 0, ceil toward +Infinity
const values = [2.7, -2.7, 2.3, -2.3];
for (const v of values) {
console.log(
v,
'| floor', Math.floor(v),
'| trunc', Math.trunc(v),
'| ceil', Math.ceil(v),
);
}
// round rounds .5 toward +Infinity: -2.5 becomes -2 not -3, and -0.5 lands on -0
console.log('round(-2.5) =', Math.round(-2.5), '| round(2.5) =', Math.round(2.5));
console.log('round(-0.5) =', Math.round(-0.5), '| floor(-0.5) =', Math.floor(-0.5));
// trunc chops the fraction off, same for both signs - for "drop the decimals" rather than "round down"
console.log('trunc(-2.9) =', Math.trunc(-2.9), '| trunc(2.9) =', Math.trunc(2.9));
// Decide the direction before bucketing/indexing: whether -0.2 lands in bucket 0 or -1 changes membership
console.log('floor(-0.2) =', Math.floor(-0.2), '| trunc(-0.2) =', Math.trunc(-0.2));