Pascal **定义(指数)

时间:2013-03-13 03:54:44

标签: operators pascal exponent

我在扩展Pascal中寻找**指数运算的定义。我一直在寻找一段时间,似乎无法找到它。

i.e 2**3 = 8

1 个答案:

答案 0 :(得分:4)

在FreePascal中,它是在数学单元中实现的:

operator ** (bas,expo : float) e: float; inline;
  begin
    e:=power(bas,expo);
  end;


operator ** (bas,expo : int64) i: int64; inline;
  begin
    i:=round(intpower(bas,expo));
  end;

function power(base,exponent : float) : float;

  begin
    if Exponent=0.0 then
      result:=1.0
    else if (base=0.0) and (exponent>0.0) then
      result:=0.0
    else if (abs(exponent)<=maxint) and (frac(exponent)=0.0) then
      result:=intpower(base,trunc(exponent))
    else if base>0.0 then
      result:=exp(exponent * ln (base))
    else
      InvalidArgument;
  end;

function intpower(base : float;const exponent : Integer) : float;

  var
     i : longint;

  begin
     if (base = 0.0) and (exponent = 0) then
       result:=1
     else
       begin
         i:=abs(exponent);
         intpower:=1.0;
         while i>0 do
           begin
              while (i and 1)=0 do
                begin
                   i:=i shr 1;
                   base:=sqr(base);
                end;
              i:=i-1;
              intpower:=intpower*base;
           end;
         if exponent<0 then
           intpower:=1.0/intpower;
       end;
  end;