2017-07-19 163 views
1

我需要有人可以幫助如何在序言奇數倍

Define a predicate oddMultOf3/1 that determines whether an integer is an odd multiple of 3. A user should be able to enter the predicate with an integer, e.g. oddMultOf3(42) and evaluate to either true or false. If the given parameter is not an integer, your predicate should display the message 「ERROR: The given parameter is not an integer」.

做3奇數倍,他們要求我做這

oddMultOf3(171). 
true. 
oddMultOf3(100). 
false. 
oddMultOf3(12). 
false. 
oddMultOf3(4.2). 
ERROR: The given parameter is not an integer 
oddMultOf3(-9). 
true. 

,但我不斷收到錯誤,每次當我嘗試。

這是我的代碼

oddMultOf3(N) :- Y is N mod 3, Y=0.

+0

這是三倍的奇數倍嗎? –

+0

'Y是N模3,Y = 0'是3的倍數。現在你怎麼認爲你可能確定'N'是奇數?只需添加該條件即可。 – lurker

+0

@lurker對,所以添加一個條件來檢查N mod 2是否爲0呢?因爲例如30是偶數的3的倍數。 –

回答

1

據我所知3的奇數倍意味着N是一個整數,N/3是一個整數,N/3(如)。因此,這意味着,如果執行模6,它必須是3

居然有2箱子這裏:

  • N不是整數,在我們顯示錯誤的話,也許我們應該也是fail。所以:

    oddMultOf3(N) :- 
        \+ integer(N), 
        !, 
        print("ERROR: The given parameter is not an integer"), 
        fail. 
    
  • 否則,我們檢查,如果N mod 6等於3

    oddMultOf3(N) :- 
        3 is N mod 6. 
    

或者將其組合在一起:

oddMultOf3(N) :- 
    \+ integer(N), 
    !, 
    print("ERROR: The given parameter is not an integer"), 
    fail. 
oddMultOf3(N) :- 
    3 is N mod 6. 

然後我們在swi獲得:

?- oddMultOf3(171). 
true. 

?- oddMultOf3(100). 
false. 

?- oddMultOf3(12). 
false. 

?- oddMultOf3(4.2). 
"ERROR: The given parameter is not an integer" 
false. 

?- oddMultOf3(-9). 
true. 
+0

非常感謝,但是當我厭倦了你的代碼時,它給了我錯誤的結果,例如:oddMultOf3(171)。必須是真實的,但在你的代碼給我虛假 – user8286060

+0

@ user8286060:固定。 –