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

查看:44
本文介绍了你如何使用 prolog 在多行上打印星星 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.

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

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