是否有可能提高效率?
Is it possible to make this more efficient?
我写了一个 Google Sheets 脚本来计算在给定 x 顾客数量和每瓶 y 注射量的情况下需要的瓶子数量。
即
=BOTTLES_REQUIRED(1,22)
#=>1
=BOTTLES_REQURIED(22,22)
#=>1
=BOTTLES_REQUIRED(23,22)
#=>2
function BOTTLES_REQUIRED(customers, shots_per_bottle) {
var bottles_required = 1;
var shots = 0;
for(var i = 0; i < customers; i++) {
shots++;
if( shots > shots_per_bottle ) {
bottles_required++;
shots = 0;
}
}
return bottles_required;
}
虽然有时 运行 需要一段时间,但有没有更有效的写法?
为什么不为此使用数学?
function BOTTLES_REQUIRED(customers, shots_per_bottle) {
return Math.ceil(customers / shots_per_bottle);
}
看看这个jsFiddle example。
我写了一个 Google Sheets 脚本来计算在给定 x 顾客数量和每瓶 y 注射量的情况下需要的瓶子数量。
即
=BOTTLES_REQUIRED(1,22)
#=>1
=BOTTLES_REQURIED(22,22)
#=>1
=BOTTLES_REQUIRED(23,22)
#=>2
function BOTTLES_REQUIRED(customers, shots_per_bottle) {
var bottles_required = 1;
var shots = 0;
for(var i = 0; i < customers; i++) {
shots++;
if( shots > shots_per_bottle ) {
bottles_required++;
shots = 0;
}
}
return bottles_required;
}
虽然有时 运行 需要一段时间,但有没有更有效的写法?
为什么不为此使用数学?
function BOTTLES_REQUIRED(customers, shots_per_bottle) {
return Math.ceil(customers / shots_per_bottle);
}
看看这个jsFiddle example。