尽管满足循环条件,循环仍继续

时间:2015-07-28 21:00:03

标签: delphi delphi-7

我创建了一个使用牛顿方法计算正实数的整数根的函数。它适用于我尝试的每个案例,除了2的平方根。

只要X [n]不等于X [n-1],我就有一个迭代Newton方法的重复循环。对于2的平方根,我最终得到X [n] = 1.4142135624并且X [n-1] = 1.4142135624,但是尽管X [n]等于X [n-1],循环仍然继续。我该如何解决这个问题?这是Delphi语言中的错误吗? (这是在Delphi 7 - SE中制作的)

function IntPower(Const Base : Real; Const Power : Integer):Real; //Integer power function
var
  K : Integer;
  Output : Real;
begin
  Output := 1;
  If Power >= 0 then
    For K := 1 to Power do
    begin
      Output := Output * Base;
    end
  else
    For K := -1 downto Power do
    begin
      Output := Output / Base;
    end;
  Result := Output;
end;

function IntRoot(Base : Real; Root : Integer):Real;
var
  K : Integer;
  Output, Greater, Less, Previous : Real;
begin
  if (Root < 0) AND (Base = 0) then
  begin
    Result := 0;
    Exit;
  end;
  if (Root = 1) OR (Base = 1) then
  begin
    Result := Base;
    Exit;
  end;
  K := 2;
  Previous := 0;
  if Root < 0 then
  begin
    Root := Root * (-1);
    Base := 1/Base;
  end;
  //BEGINNING OF INITIAL GUESS//
  if Base < 1 then
  begin
    Greater := 1;
    Less := 0;
    While Less = 0 do
    begin
      if IntPower(1/K,Root) > Base then
        Greater := 1/K
      else if IntPower(1/K,Root) < Base then
        Less := 1/K
      else
      begin
        Result := 1/K;
        Exit;
      end;
      Inc(K);
    end;
  end
  else if Base > 0 then
  begin
    Greater := 0;
    Less := 1;
    While Greater = 0 do
    begin
      if IntPower(K,Root) > Base then
        Greater := K
      else if IntPower(K,Root) < Base then
        Less := K
      else
      begin
        Result := K;
        Exit;
      end;
      Inc(K);
    end;
  end;
  Output := (Greater+Less)/2;
  //END OF INITIAL GUESS//
  Repeat
    Previous := Output;
    Output := Previous - (IntPower(Previous,Root)-base)/((Root)*IntPower(Previous,Root-1));
  Until(Output = Previous);
  Result := Output;
end;

begin
  Writeln(FloatToStr(IntRoot(2,2));
  Readln;
end.

是的,我知道我为n&lt; 0并且我知道n ^的0 ^ n存在问题。 0

0 个答案:

没有答案
相关问题