Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Calculating the nth Power of a Number

C Language Examples - Calculating the nth Power of a Number

C Language Examples C Language Examples

Calculate the nth power of a number, for example: 23, where 2 is the base and 3 is the exponent.

Example - Using while

#include

<

stdio.h

int

main

(

)

{

int

base

,

exponent

;

long

long

result

=

1

;

printf

(

"

Base:

"

)

;

scanf

(

"

%d

"

, &

base

)

;

printf

(

"

Exponent:

"

)

;

scanf

(

"

%d

"

, &

exponent

)

;

while

(

exponent

!=

0

)

{

result

*=

base

; --

exponent

;

}

printf

(

"

Result: %lld

"

,

result

)

;

return

0

;

}

Running result:



基数: 2

指数: 3

结果:8

Example - Using the pow() function

#include

<

stdio.h

#include

<

math.h

int

main

(

)

{

double

base

,

exponent

,

result

;

printf

(

"

Base:

"

)

;

scanf

(

"

%lf

"

, &

base

)

;

printf

(

"

Exponent:

"

)

;

scanf

(

"

%lf

"

, &

exponent

)

;

// Calculate the result

result

=

pow

(

base

,

exponent

)

;

printf

(

"

%.1lf^%.1lf = %.2lf

"

,

base

,

exponent

,

result

)

;

return

0

;

}

Running result:



基数: 2

指数: 3

2.0^3.0 = 8.00

Example - Recursion

#include

<

stdio.h

int

power

(

int

n1

,

int

n2

)

;

int

main

(

)

{

int

base

,

powerRaised

,

result

;

printf

(

"

Base:

"

)

;

scanf

(

"

%d

"

,&

base

)

;

printf

(

"

Exponent (positive integer):

"

)

;

scanf

(

"

%d

"

,&

powerRaised

)

;

result

=

power

(

base

,

powerRaised

)

;

printf

(

"

%d^%d = %d

"

,

base

,

powerRaised

,

result

)

;

return

0

;

}

int

power

(

int

base

,

int

powerRaised

)

{

if

(

powerRaised

!=

0

)

return

(

base

power

(

base

,

powerRaised

1

)

)

;

else

return

1

;

}

C Language Examples C Language Examples