prolog - Prolog中的猜数字游戏
问题描述
我正在尝试构建一个简单的程序,其中用户有 3 次尝试猜测一个数字,但存在编译错误,我不知道问题出在哪里。
actual_number(500).
actual_number(Num).
start:-
write('Enter your first guess'), nl,
read(Guess1),
Guess1 =\= Num -> write('Wrong you have 2 tries left'),
read(Guess2);
Guess1 == Num -> write('Correct'),!.
Guess2 =\= Num -> write('Wrong you have 1 try left'),
read(Guess3);
Guess2 == Num -> write('Correct'),!.
Guess3 =\= Num -> write('Wrong the number was 500'),!;
Guess3 == Num -> write('Correct').
解决方案
我使用Swish来测试代码。与以下第一个代码剪切的主要区别在于以下版本更加结构化并且不使用剪切。由于您使用的是 If-the-else 指令,这些指令本身就使用了削减,因此不需要削减。请注意,;
调用的析取 ( ) 与合取 ( ) 的优先级不同,
。使用括号来定义析取的范围以及 if-then-else 必须为真才能触发的语句。
actual_number(500).
start:-
actual_number(Num),
write('Enter your first guess'), nl,
read(Guess1),
( Guess1 == Num
-> write('Correct')
; write('Wrong you have 2 tries left'), nl,
read(Guess2),
( Guess2 == Num
-> write('Correct')
; write('Wrong you have 1 try left'), nl,
read(Guess3),
( Guess3 == Num
-> write('Correct')
; write('Wrong the number was '),
write(Num)
)
)
).
第二种方法计算尝试的次数并且原则上相同,只是代码更加prolog-ish。
actual_number(500).
start:-
write('Enter your first guess'), nl,
start(3).
start(N):-
N>0,
actual_number(Num),
read(Guess),
( Guess == Num
-> write('Correct')
; Nnew is N-1,
write('Wrong you have '),
write(Nnew),
write(' tries left'), nl,
start(Nnew)
).
start(0):-
actual_number(Num),
write('Wrong the number was '),
write(Num).
推荐阅读
- css - Vimeo OTT 中的自定义 CSS
- storage - Jfrog 中的二进制文件到底是什么
- javascript - 如何根据变量运行功能未知的次数?
- java - 使用 JPA 进行乐观锁定(休眠)
- android - 找不到 com.android.tools.build:gradle:1.3.50
- postgresql - Slick-PG 和 PostgreSQL 12 是否稳定运行?
- java - 在 Active Directory 中更新用户失败(使用 Boomi 映射)
- jsf - 数据表之外的 PrimeFaces 全局过滤器不起作用
- visual-studio-code - VSCode烦人的问题焦点行为,不断跳到问题
- javascript - 如何使用 Laravel 创建数据透视表,如 Excel 数据透视表