我想询问我制作的多项选择课程。我混淆了如何连续存储一个值,所以我可以在程序结束时根据已经存储的值的总和得出结论。
start :- program.
program :-
write('This is question number 1'),nl,
write('A'),nl,
write('B'),nl,
write('C'),nl,
read(Choice),nl,
(
%case1
Choice='a'->nl,
=================================
A = A + 1 <--- Right Here,
And then go to Question 2.
=================================
%case2
Choice='b'->nl,
=================================
B = B + 1 <--- Right Here,
And then go to Question 2.
=================================
%case3
Choice='c'->nl,
=================================
C = C + 1 <--- Right Here,
And then go to Question 2.
=================================
%case_default
write('Wrong Code')
).
所以我可以得出这样的结论,
===================================
if B < A > C then you're an A.
if A < B > C then you're a B.
if A < C > B then you're a C.
===================================
以前非常感谢你:)
答案 0 :(得分:2)
存储值的方法有很多种。您可能会想到的 - 存储一些计数器并根据给定的答案更新它们 - 可能会导致一些复杂的情况。使用计数器的代码示例:
question('Choose a, b or c: ').
question('Choose again a, b or c: ').
question('Think before you choose a, b, or c: ').
ask :-
findall(Q, question(Q), Questions),
ask_and_count([0,0,0], [A,B,C], Questions),
max_list([A,B,C], Max),
nth1(Index,[A,B,C],Max),
nth1(Index,[a,b,c],Answer),
print('You''re a(n) '), print(Answer), nl.
ask_and_count(Count, Count, []) :-
print('Thank you, that''s all questions!'), nl, !.
ask_and_count(InCount, OutCount, [Q | Questions]) :-
print(Q),
read_abc(Ans),
increase(Ans, InCount, NewCount),
ask_and_count(NewCount, OutCount, Questions).
read_abc(A) :-
read(A),
member(A, [a,b,c]),
!.
read_abc(A) :-
print('Only a, b and c are accepted! Answer again: '),
read_abc(A).
increase(a, [A, B, C], [X, B, C]) :- X is A + 1.
increase(b, [A, B, C], [A, X, C]) :- X is B + 1.
increase(c, [A, B, C], [A, B, X]) :- X is C + 1.
示例输入和输出:
?- ask.
Choose a, b or c: b.
Choose again a, b or c: c.
Think before you choose a, b, or c: c.
Thank you, that's all questions!
You're a(n) c
也许我可以激励你以另一种方式做到这一点,在我看来这更像是“prologish”,因为它依赖于列表并导致更简单的代码:
question('Choose a, b or c: ').
question('Choose again a, b or c: ').
question('Think before you choose a, b, or c: ').
read_abc(A, Choices) :-
read(A),
member(A, Choices),
!.
read_abc(A, Choices) :-
print('Only '), print(Choices), print(' are accepted! Try again: '),
read_abc(A, Choices).
ask(Answers) :-
findall(Ans, (question(Q), print(Q), read_abc(Ans, [a,b,c])), Answers).
start :-
ask(Answers),
print(Answers).
示例输入和输出:
?- start.
Choose a, b or c: c.
Choose again a, b or c: b.
Think before you choose a, b, or c: c.
[c,b,c]
true.
在列表中包含所有答案后,您可以简单地计算每个答案的出现次数。
存储选择的其他方式是使用assert
和retract
谓词。 Expert systems do that。使用assert和retract时,您可以使用一些谓词,如其他编程语言中已知的全局变量。