2017-07-19 60 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是给定的。 –