Home > Article > Backend Development > Write a method to calculate power function in C language
How to write the exponentiation function in C language
Exponentiation (exponentiation) is a commonly used operation in mathematics, which means multiplying a number by itself several times. In C language, we can implement this function by writing a power function. The following will introduce in detail how to write a power function in C language and give specific code examples.
double power(double base, int exponent);
double power(double base, int exponent) { if (exponent >= 0) { // 正指数的情况 } else { // 负指数的情况 } }
double result = 1.0; for (int i = 0; i < exponent; i++) { result *= base; }
double positiveResult = 1.0; // 存储正指数的乘方结果 for (int i = 0; i < -exponent; i++) { positiveResult *= base; } double result = 1.0 / positiveResult;
return result;
To sum up, the following is a complete code example of the power function:
double power(double base, int exponent) { if (exponent >= 0) { double result = 1.0; for (int i = 0; i < exponent; i++) { result *= base; } return result; } else { double positiveResult = 1.0; for (int i = 0; i < -exponent; i++) { positiveResult *= base; } double result = 1.0 / positiveResult; return result; } }
Using this power function, we can easily calculate the power of multiple numbers. , and get the result.
Summary: This article introduces how to write a power function in C language. By judging the sign of the exponent, use a loop to continuously multiply the bases, and finally take the reciprocal to calculate the power result. This exponentiation function can be easily applied to various scenarios that require exponentiation calculations.
The above is the detailed content of Write a method to calculate power function in C language. For more information, please follow other related articles on the PHP Chinese website!