我是该语言的新手,并试图找出一个返回二次方程根的简单函数的格式.
discriminant(A,B,C) ->
B * B - 4 * A * C.
get_roots(A,B,C) when A == 0 -> error;
get_roots(A,B,C) when discriminant(A,B,C) == 0 -> [(-B/(2*A))];
get_roots(A,B,C) when discriminant(A,B,C) > 0 ->
D = discriminant(A,B,C);
[((-1 * B + math:sqrt(D)) / 2 * A), ((-1 * B - math:sqrt(D)) / 2 * A)];
get_roots(A,B,C) when discriminant(A,B,C) < 0 -> [].
Run Code Online (Sandbox Code Playgroud)
我做的语法错误是什么?我在shell中输入"c(ps04)"时得到的错误,其中ps04.erl是我编写函数的文件,是:
ps04.erl:15: syntax error before: '['
ps04.erl:23: Warning: variable 'Head' is unused %for a different function defined later
error
Run Code Online (Sandbox Code Playgroud)
你不能在守卫中使用一个功能,所以get_roots(A,B,C) when discriminant(A,B,C) == 0是禁止的.由@Amon提及,有一个分号应该用逗号代替.我会写这样的函数:
get_roots(0,0,_) -> [];
get_roots(0,B,C) -> [-C/B];
get_roots(A,B,C) -> get_roots(A,B,C,A*A-4*B*C).
get_roots(A,B,C,0) -> [-B/(2*A)];
get_roots(A,B,C,D) when D > 0 ->
RD = math:sqrt(D),
[(-B+RD)/(2*A),(-B-RD)/(2*A)];
get_roots(_,_,_,_) -> [].
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |