你如何使用序言在多行上打印星星 n 次 [英] how do you print stars n amount of times on multiple lines using prolog

查看:11
本文介绍了你如何使用序言在多行上打印星星 n 次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印星星 '*' n 时间

i need to print stars '*' n amount of time

推荐答案

很简单的解决方案:

star(0).
star(N):-
    N > 0,
    foreach(between(1,N,_),write('*')),nl,
    N1 is N-1,
    star(N1).

?- star(3).
***
**
*
true
false

您的代码中的一个问题是,如果您使用 N-1 调用 star,则在下一次迭代中 N 将被统一与 N-1 (当你写它,它不执行算术运算).相反,您应该执行 N1 is N-1,然后使用 N-1 调用 star.然后还有其他的问题……看我的代码有个思路.

One of the problem in your code is that if you call star with N-1, at the next iteration N will be unified with N-1 (as you write it, it does not performs the arithmetic operation). Instead you should do N1 is N-1 and then call star with N-1. Then there are other problems... Look at my code to have an idea.

这篇关于你如何使用序言在多行上打印星星 n 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆