Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么内存堆不足,为什么数组中的最后一项不';t步骤+;0.1?_Javascript - Fatal编程技术网

Javascript 为什么内存堆不足,为什么数组中的最后一项不';t步骤+;0.1?

Javascript 为什么内存堆不足,为什么数组中的最后一项不';t步骤+;0.1?,javascript,Javascript,为什么内存堆不足,为什么数组中的最后一项不执行+0.1步 const array = []; const step = 0.1; do { const item = array[array.length - 1] ? array[array.length - 1] : 0; array.push(item + step); } while (array[array.length - 1] !== 100); 使用小于而不是不等于,例如while(array[array.leng

为什么内存堆不足,为什么数组中的最后一项不执行+0.1步

const array = [];
const step = 0.1;
do {
    const item = array[array.length - 1] ? array[array.length - 1] : 0;
    array.push(item + step);
} while (array[array.length - 1] !== 100);

使用小于而不是不等于,例如
while(array[array.length-1]<100)
,因为由于浮点运算的性质,您将无法精确获得100

请参阅下面程序的输出

console.log(generateSequence(01100,0.1));
函数生成顺序(开始、结束、步骤){
让结果=[];
做{
const prev=result[result.length-1]?result[result.length-1]:0;
结果:推送(上一步+下一步);
}while(result[result.length-1]<100);
返回结果;
}

作为控制台包装{top:0;最大高度:100%!重要;}
使用
while(array[array.length-1]<100)
,因为由于四舍五入,您将无法精确获得100。@Mr.polywhill由于浮点错误;或者缺少四舍五入
0.1
不能用二进制精确表示,因此会出现浮点错误。????array=[0]array.push(0+0.1)console.log(array[array.length-1])//0.1这是否回答了您的问题@和
0.1+0.1+0.1
!=<代码>0.3因为浮点值是如何工作的。我的任务是将数组从0推到100,当步长必须为0.1时,请参见底部的更新代码。