Вопрос

I'm a complete noob in Prolog. I'm working on an assignment where I create a change counter that can take a total S (in cents), 0 <= S <= 100. So I need to show the number of half dollars, quarters, dimes, nickels.

Here's my code:

change(S,H,Q,D,N,P) :-
            member(H,[0,1,2]),      /* Half-dollars */      
            member(Q,[0,1,2,3,4]),  /* quarters */  
            member(D,[0,1,2,3,4,5,6,7,8,9,10]) ,    /* dimes */    
            member(N,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]), 
            /* ^^ nickels ^^ */

            S is 50*H + 25*Q +10*D + 5*N,
            S =< 100,
            P is 100-S.

so my issue is when i try and calculate something like ?- change(87,0,3,D,1,P). where the amount i am inputing is 87 cents and i need 3 quarters and 1 nickel..... i get an error stating uncaught exception: error(existence_error(procedure,change/6),top_level/0)

With my last 3 lines of code I thought I was handling the amount given correctly. Do I need to make an additional rule regarding the amount given?

Это было полезно?

Решение

You miss the cents! And I suggest to use between/3 to express the ranges:

...,
between(0,100,Cents),
...,

...,
S is 50*H + 25*Q +10*D + 5*N + Cents,
...,

test:

?- change(87,H,Q,D,N,Cents,P).
H = Q, Q = D, D = N, N = 0,
Cents = 87,
P = 13 ;
H = Q, Q = D, D = 0,
N = 1,
Cents = 82,
P = 13 ;

WRT error(existence_error... I think you need to compile your script...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top