2017-07-19 106 views
1

我需要在這Turbo Pascal的問題有所幫助:渦輪帕斯卡爾在家工作

兩個整數被說成是兄弟,如果N1的每個數字在N2出現至少一次,反之亦然。例如:如果N1 = 1164和N2 = 614程序將顯示N1和N2是兄弟,如果N1 = 504和N2 = 455程序將顯示N1和N2不是兄弟

我的問題是:如何檢查是否這兩個整數是兄弟還是不是?這是我的工作:

function brother(n1, n2: integer): boolean; 
var 
    test: boolean; 
    ch1, ch2: string; 

begin 
    chr(n1, ch1); 
    chr(n2, ch2); 
    i := 0; 
    repeat 
    j := 0; 
    i := i + 1; 
    test := false; 
    repeat 
     j := j + 1; 
     if ch1[i] = ch2[j] then 
     test := true; 
    until (test = true) or (j = length(ch2)); 
    until (test = false) or (i = length(ch1)); 
    brother := test; 
end; 

,當我運行它,它總是打印(「整數是兄弟」),甚至當我把 504和455,我想知道在哪裏的錯誤是。

+0

下面是一些對你的lubbely僞代碼......我覺得你的問題的一部分,從功能的莖是有點迷茫......試試這個:做一個循環(通過str1中的每個字符循環),其使用功能,本身一次傳遞一個字符(str1的時間爲1個字符),並查看字符是否存在於給定的字符串(str2)中,增加「是」計數器或者在任何時間是否爲「否」,然後停止所有測試。一旦你到達了給定字符串(str2)的末尾並且有一個yes =給定的字符串= string的長度就是兄弟。 –

+0

你的代碼看起來不對。 'chr'是一個將'integer'轉換爲單個'char'的僞函數。我假設在你的真實代碼中,你有類似'str(n1,ch1);'的東西。你也有'(n1,n2:整數)'作爲你的參數列表(我糾正了這個),那也不是可編譯的代碼。 –

回答

0

嘗試這樣代替:

function contains(s: string; ch: char): boolean; 
var 
    i: integer; 
begin 
    contains := false; 
    for i := 1 to length(s) do 
    if s[i] = ch then 
     contains := true; 
end; 

function brother(n1, n2: integer): boolean; 
var 
    test: boolean; 
    ch1, ch2: string; 
    i: integer; 
begin 
    str(n1, ch1); 
    str(n2, ch2); 
    test := true; { assume "brotherhood" } 

    for i := 1 to length(ch1) do 
    if not contains(ch2, ch1[i]) then 
     test := false; { obviously no brothers after all } 

    { must test both ways, so (n1=455, n2=504) fails too } 
    for i := 1 to length(ch2) do 
    if not contains(ch1, ch2[i]) then 
     test := false; 

    brother := test; 
end; 

相反的for,您可以使用repeat until了。 !

+0

它的工作,也與__repeat__ –

-1

你需要帕斯卡else/if變種,有你必須檢查它的平等。

+1

我很瞭解帕斯卡,但我不知道這是如何回答的。檢查什麼平等?那個人可能不得不使用if或else是給定的。 –