0

我有一个数字列表,我想将它们相加,然后将它们乘以一个常数。

addList := proc(a::list,b::integer)::integer;
local x,i,s;
description "add a list of numbers and multiply by a constant";
x:=b;
s:=0;
for i in a do
    s:=s+a[i];
end do;
s:=s*x;
end proc;

sumList := addList([2, 2, 3], 2) 工作正常,但同时 sumList := addList([20, 20, 30], 2) 给出错误。有人可以指出错误吗?

4

2 回答 2

2

在 for 循环中,您执行s:=s+a[i]但 i 已设置为 a 中的值之一 - 而不是值的索引。第一次通过修复将只是将上面的语句更改为s:=s+i.

您也可以将函数编写为

proc(a::list,b::integer)::integer; 
   convert(a,`+`)*b; 
end;
于 2013-06-03T03:53:06.307 回答
1

更短的还有

addList:= (a,b)-> `+`(a[])*b;
于 2013-06-04T00:30:52.103 回答