我想编写一个在Prolog中返回更改的程序,我尝试了这个谓词,但我不确定它,因为我想要像在C / C ++程序中那样做。如果有人对此进行了更正,我会很感激。
dollar(100).
quarter(25).
dime(1).
return(0,0,0).
return(Amount_recieved,Amount_due,Change) :-
Change is Amount_recieved - Amount_due.
dollar(100) is Change / 100 , Change is Change mod 100.
quarter(25) is Change /25 , Change is Change mod 25.
dime(1) is Change
答案 0 :(得分:1)
我提出以下基于结构amount/3
的解决方案,其中包含美元数(第一个值),季度数(第二个值)和角钱数(第三个值)
getAmountInDimes(amount(Do, Qu, Di), AmountInDimes) :-
AmountInDimes is (Do * 100) + (Qu * 25) + Di.
getAmountTriple(AmountInDimes, amount(Do, Qu, Di)) :-
Do is AmountInDimes div 100,
Mid is AmountInDimes mod 100,
Qu is Mid div 25,
Di is Mid mod 25.
computeChange(AReceived, ADue, Change) :-
getAmountInDimes(AReceived, ARDimes),
getAmountInDimes(ADue, ADDimes),
ARDimes >= ADDimes,
CDimes is ARDimes - ADDimes,
getAmountTriple(CDimes, Change).
以下是使用示例
computeChange(amount(20, 0, 0), amount(15, 2, 12), Ch)
将Ch
与amount(4,1,13)
统一起来。
另一个例子
computeChange(amount(20, 0, 0), amount(15, 2, 12), amount(Do, Qu, Di))
直接将Do
与4,Qu
与1和Di
与13直接统一。