在prolog中求解二次方程

时间:2014-10-20 20:59:38

标签: prolog instantiation-error

我在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

2 个答案:

答案 0 :(得分:1)

在最后两个谓词(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).

答案 1 :(得分: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
 ).