Kaboom
Kaboom

Reputation: 1

Using Powers in Pascal

program Project1;

var
  num1: integer;
  num2: integer;
  answer: integer;
begin
  writeln('This program will accept two input values and raise the first number to the power of the second value');
  writeln('Please enter the first number');
  readln(num1);
  writeln('Please enter the second number');
  readln(num2);

  writeln(num1**num2);
end.

This is my code in Pascal. I want to enter two values and answer will return the first value of the power to the second. Can anyone help?

Upvotes: 0

Views: 7235

Answers (3)

abdo Information
abdo Information

Reputation: 73

Hello I think this function will be help you.

Program Power_fun;
    {$APPTYPE CONSOLE}
    Function Power(x, p: Double): Double;
      Var negative: Double;
    Begin
        If(x<0) Then
        Begin
          If(Round(p) mod 2 = 0) Then negative := 1
            Else negative := -1;
          x := -x;
        End
        Else negative := 1;
        Power := Exp(p*(Ln(x)))*negative;
    End;
Begin
    Writeln(Power(2, 2));
    Writeln(Power(5, 2));
    Writeln(Power(-2, 2));
    Writeln(Power(-2, 3));
    Writeln(Power(-5, 3));
    readln;
End.

Upvotes: 0

Bogdan Doicin
Bogdan Doicin

Reputation: 2416

Another way is to use a for loop:

pow:=1;
for i:=1 to num2 do
 pow:=pow*num1;

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

The power operator ** for numeric types is not defined for numeric types. However, it is a recognised operator and the math unit defines overloads for integer and floating point types. So you must use that unit and then your code compiles and runs correctly.

Add

uses
  math;

to your code.

Upvotes: 2

Related Questions