我需要一种更有效的方法来将解析后的数字中的每1值增加0.0001。类似于下面引用的代码,但是如果输入的数字太大,则不会导致浏览器崩溃。
function example(amm) {
var base = 1;
var ret = 0;
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
return [base,ret];
};
var total = example(100);
console.log(total[0].toFixed(4));
console.log(total[1].toFixed(4));
更新:我需要退货和退货
最佳答案
经过分析,您的功能可以简化为:
function example(amm) {
var base = 1 + amm*0.0001;
var ret = amm + 0.0001 * (amm)*(amm + 1)/2;
return [base.toFixed(4), ret.toFixed(4)];
}
console.log(example(100));
console.log(example(200));
console.log(example(1000));
console.log(example(2000));
为什么?
base = 1
ret = 0
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
now, the above is just:
base = 1 + amm*0.0001 // it sums 0.0001 amm times and has an initial value of 1
ret = 1 + (1.0001) + (2.0002) + (3.0003) + (4.0004) + ... + (amm + 0.0001*amm)
= 1*amm + 0.0001*((amm)*(amm + 1)/2)
= amm + 0.0001*((amm)*(amm + 1)/2)
一些测试:
function example1(amm) {
var base = 1;
var ret = 0;
for(var i=1; i<=amm; i++) {
base += 0.0001;
ret += base;
}
return [base.toFixed(4), ret.toFixed(4)];
}
function example2(amm) {
var base = 1 + amm*0.0001;
var ret = amm + 0.0001 * (amm)*(amm + 1)/2;
return [base.toFixed(4), ret.toFixed(4)];
}
console.log(example1(100) + ' === ' + example2(100));
console.log(example1(1564) + ' === ' + example2(1564));
console.log(example1(21343) + ' === ' + example2(21343));
console.log(example1(132) + ' === ' + example2(132));
console.log(example1(0) + ' === ' + example2(0));
console.log(example1(1) + ' === ' + example2(1));