2

我在prolog中遇到了二次方程实现的问题。我知道一些基础知识,但同时我无法理解 swish.swi 控制台的输出。如果您对我的错误提供任何帮助或建议,我将不胜感激。

delta(A, B, C, D):- D is B*B - 4*A*C.

equation(A,B,C,X):- D1<0,delta(A,B,C,D1),X is 0. % or false... but how to retur false there?
equation(A,B,C,X):- D1 =:= 0,delta(A,B,C,D1),X is -B/2*A. 
equation(A,B,C,X): D1>0,delta(A,B,C,D1),X is -B-sqrt(D1)/2*A.
equation(A,B,C,X): D1>0,delta(A,B,C,D1),X is -B+sqrt(D1)/2*A.

runnign 后出现两个错误equation(2, 0, 1, X).

Full stop in clause-body?  Cannot redefine ,/2
</2: Arguments are not sufficiently instantiated
4

2 回答 2

1

在最后 2 个谓词(D>0 的谓词)中,您忘记在“:”之后写“-”。您的代码运行良好,这只是一个 sintax 错误。下面我为您更正了代码:

delta(A, B, C, D):- D is B*B - 4*A*C.
equation(A,B,C,X):- D1<0, delta(A,B,C,D1), X is 0. 
equation(A,B,C,X):- D1 =:= 0, delta(A,B,C,D1), X is -B/2*A.
equation(A,B,C,X):- delta(A,B,C,D1), D1>0, X is ((-1*B-sqrt(D1))/2*A).
equation(A,B,C,X):- delta(A,B,C,D1), D1>0, X is ((-1*B+sqrt(D1))/2*A).
于 2020-05-09T11:01:41.577 回答
0

关于

参数没有充分实例化

您必须交换 delta/4 和测试。此外,最好使用 if/then/else,以避免重新计算结果:

equation(A,B,C,X) :-
 delta(A,B,C,D1),
 (  D1 < 0
 -> X is 0
 ;  D1 =:= 0
 -> X is -B/2*A
 ;  X is -B-sqrt(D1)/2*A
 ).
于 2014-10-20T21:13:12.477 回答