divide_by(X, D, I, R) :- (D > X), I is 0, R is X.
divide_by(X, D, I, R) :-
X >= D,
X_1 is X - D,
I_1 is I + 1,
divide_by(X_1, D, I_1, R),
R is X_1.我正在尝试编写一个程序,它将接受两个参数(X和D)并返回迭代次数(I)和余数(R),这样当用户输入: divide_by(8,3,I,R)时,它就可以显示X/D的结果。例如。
当跟踪代码时,我知道i是不正确的,因为第一个增量使它等于0,因此计数是错误的。但我不知道如何声明i为0,而不在每次循环递归时重置。(我不想在查询中将i声明为0)
我还意识到,当它完成递归(当X
有没有人能教我怎么解决这个问题?
发布于 2013-02-22 01:59:18
您需要引入一个累加器并使用一个辅助谓词,如下所示:
divide(_,0,_,_) :- !, fail . % X/0 is undefined and so can't be solved.
divide(0,_,0,0) :- !. % 0/X is always 0.
divide(X,Y,Q,R) :- % the ordinary case, simply invoke the
divrem(X,Y,0,Q,R) % helper with the accumulator seeded with 0
.
divrem(X,Y,Q,Q,X) :- % if X < Y, we're done.
X < Y . %
divrem(X,Y,T,Q,R) :- % otherwise...
X >= Y , % as long as X >= Y,
X1 is X - Y , % compute the next X
T1 is T + 1 , % increment the accumulator
divrem(X1,Y,T1,Q,R) % recurse down
. % Easy!https://stackoverflow.com/questions/15008586
复制相似问题