【发布时间】:2018-04-28 11:23:26
【问题描述】:
我目前正在尝试为谷歌工作表编写一个自定义函数,给定一个一维范围,告诉我在该范围内累积总和达到(或超过)给定总和,或者如果累积则抛出错误总和永远不会达到给定的总数。
例如,给定这样的范围:
10
12
14
15
18
3
8
9
如果请求的总和是“24”,则函数将返回 3。
如果请求的总和是“60”,则函数将返回 5。
如果请求的总和是“1000”,则函数会抛出错误。
我目前卡在的代码是:
function SUBTOTALPOSITION(range,sum)
{
/**
* Finds the position in a one-dimensional range where
* the cumulative sum reaches the requested subtotal
*
* @range The range being searched (1-dimensional range only)
* @sum The cumulative sum being searched for
* @customfunction
*/
if((range.length > 1) && (range[0].length > 1))
{
throw 'range is multi-dimensional';
}
var position = 0;
var total = 0;
while(position < range.length)
{
total = total + range[position];
position++;
if(total >= sum)
{
return position;
}
}
throw 'Sum not reached';
}
我已经达到了它给我一个位置的地步,但不是正确的位置。如果我给出的总和等于或小于范围中的第一个数字,它会正确返回 1,但任何其他给定的数字总是返回 2(并且永远不会引发错误),并且我已经达到了调试能力的极限。
这段代码哪里出错了?或者有没有更好的方法来解决这个问题?这可以在没有自定义函数的情况下完成吗?
【问题讨论】:
标签: google-apps-script google-sheets custom-function