You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prolog实现1-10偶数打印:调用printn(1)返回false求助

Fixing Your Prolog Even Number Printer

Let's break down why your current code returns false when you query ?- printn(1), then fix it step by step.

What's Wrong with the Original Code?

Your code has two key issues that lead to the false result:

  • No fallback for odd starting values: When you call printn(1), the first clause (printn(10)) doesn't match. The second clause checks if X mod 2 =:= 0—since 1 is odd, this condition fails, and there's no logic to move to the next number. The clause just fails, leaving no other rules to try, so Prolog returns false.
  • Limited termination condition: Your only stop case is printn(10), but if you don't reach 10 via valid recursion steps (like starting at 1 and not handling odds), you never hit that termination rule.

Here's your original code for reference:

printn(10):- write(10). 
printn(X):- (X mod 2 =:= 0 -> write(X), Next is X+1, nl, printn(Next)).

Corrected Code

We need to add logic to handle odd numbers (by moving to the next number without printing) and a clear termination condition for when we exceed 10. Here's a robust version:

% Termination rule: stop when X is greater than 10
printn(X) :- X > 10, !.

% Print even numbers, then recurse to the next value
printn(X) :-
    X mod 2 =:= 0,
    write(X),
    nl,
    Next is X + 1,
    printn(Next).

% Skip odd numbers, just recurse to the next value
printn(X) :-
    X mod 2 =\= 0,
    Next is X + 1,
    printn(Next).

If you prefer a more concise approach using an if-else structure, this works too:

printn(X) :- X > 10, !.
printn(X) :-
    (X mod 2 =:= 0 -> write(X), nl ; true), % Print even, do nothing for odd
    Next is X + 1,
    printn(Next).

How It Works

  1. Termination first: The first rule checks if X is greater than 10—if so, we stop (the ! cut prevents unnecessary backtracking, keeping the execution clean).
  2. Even number handling: If X is even, we print it, increment X, and continue the recursion.
  3. Odd number handling: If X is odd, we just increment X and recurse without printing, ensuring we keep moving towards 10.

Now when you run ?- printn(1), you'll get the expected output:

2
4
6
8
10
true

内容的提问来源于stack exchange,提问作者Hadeer El-Zayat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:22:10