2

我需要一些帮助来解决这个 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,我想知道错误在哪里。

4

2 回答 2

1

尝试这样的事情:

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

于 2017-07-22T21:12:57.983 回答
-1

你需要帕斯卡的else/if变体,在那里你必须检查它的相等性。

于 2017-07-19T03:54:28.780 回答