There are many ways to implement exponentiation operations in C language, among which the two most commonly used methods are the loop method and the recursive method. The following will introduce each and give specific code examples.
The loop method is a relatively simple and intuitive implementation method. Through the loop, the base number is continuously multiplied, and a higher number of times can be achieved The power of . The specific code is as follows:
#include <stdio.h> double power(double x, int n) { double result = 1.0; int i; if (n >= 0) { for (i = 0; i < n; i++) { result *= x; } } else { n = -n; for (i = 0; i < n; i++) { result /= x; } } return result; } int main() { double x; int n; printf("请输入底数:"); scanf("%lf", &x); printf("请输入指数:"); scanf("%d", &n); printf("%lf 的 %d 次方等于 %lf ", x, n, power(x, n)); return 0; }
In the above code, the power
function accepts two parameters, namely the base x
and the exponent n
, returns the result of the n
power operation of x
. Among them, if n
is greater than or equal to 0, multiply x
by itself n
times through a loop; if n
is less than 0, take # The absolute value of ##n, looping through dividing
x by itself
n times.
#include <stdio.h> double power(double x, int n) { if (n == 0) { return 1.0; } else if (n > 0) { return x * power(x, n - 1); } else { return 1.0 / power(x, -n); } } int main() { double x; int n; printf("请输入底数:"); scanf("%lf", &x); printf("请输入指数:"); scanf("%d", &n); printf("%lf 的 %d 次方等于 %lf ", x, n, power(x, n)); return 0; }
power function also accepts two parameters, which are the base
x and the exponent
n, returns the result of the
n power operation of
x. Among them, when
n is equal to 0, 1 is returned; when
n is greater than 0,
x multiplied by itself to the power of
n-1 is returned. The result; when
n is less than 0, the result of dividing 1 by
x raised to the power of
-n is returned.
The above is the detailed content of How to calculate exponentiation in C language. For more information, please follow other related articles on the PHP Chinese website!